问题描述
假设我有一个模块 foo
,就像这样:
Suppose I have a module foo
like this:
export const f = x => x + 1;
export const g = x => x * 2;
我可以像这样使用这个模块:
I can use this module like this:
import { f, g } from 'foo';
console.log(f(g(2)));
或者像这样:
import * as foo from 'foo';
console.log(foo.f(foo.g(2)));
我更喜欢第二种方式,因为它可以防止模块之间的名称冲突。
I prefer the second way because it prevents name collisions between modules.
然而, import *
效率低下?它是否会阻止捆绑包(例如Rollup和Webpack)发现未使用的导入并将其删除?
However, is import *
less efficient? Does it prevent bundlers (such as Rollup and Webpack) from spotting unused imports and removing them?
推荐答案
当您从'foo'指定导入为 import {f,g}时;
你保证在编译速度和包大小方面有更好的表现,因为你只得到你需要的依赖。
When you specify imports as import { f, g } from 'foo';
you guarantee better performance in terms of speed in compilation and bundle size as you will be getting only the dependencies you need.
注意:正如loganfsmyth指出的那样,一些最近的编译器/捆绑包能够引用实际上仅使用的内容,这个IMO是一个额外的步骤,可能花费一些编译时间(虽然我没有时间对这个假设进行基准测试)。
Notes: as loganfsmyth pointed out, some recent compiler/bundle are able to reference what actually is being used only, this IMO is an additional step which could cost some compilation time (although I did not have time to benchmark this assumption).
这篇关于是“import * as”效率低于具体命名的进口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!