通配符或星号 (*) 与命名或选择性导入 es6 javascript [英] Wildcard or asterisk (*) vs named or selective import es6 javascript

查看:14
本文介绍了通配符或星号 (*) 与命名或选择性导入 es6 javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道哪一种是使用导入的最佳方式:

Just wondering which one is the best way to use import:

import * as Foo from './foo';

VS:

import { bar, bar2, bar3 } from './foo';

在效率方面,例如,我使用 webpack 来捆绑所有 JavaScript 文件.即使我没有在主代码中使用它们,第一个实际上会导入所有内容吗?

In terms of efficiency, say for example, I'm using webpack for bundling all the JavaScript files. Will the first one actually importing everything even though I'm not using them in the main code?

我能找到的一些参考资料是:

Some references that I can find are:

Airbnb 风格指南中,他们建议不要使用通配符,因此始终是默认导入对象,并且 这个.

In Airbnb style guide, they are recommending no wildcard so there will always be default import object, and this.

推荐答案

如果你使用 webpack 和新的 uglify 提供的死代码消除功能,或者使用 tree-shaking 的 rollupjs,那么未使用的导入将被剥离.

If you use webpack with the dead code elimination provided by the new uglify, or rollupjs with tree-shaking, then the unused imports will be stripped.

我部分同意 airbnb 样式指南不使用通配符导入,尽管 javascripts 通配符导入不会遭受与例如 python 或 javas 通配符导入相同的疾病,即它不会污染其他定义的变量名的范围模块(当使用 import * as moduleB from ... 时,您只能通过 moduleB.foo 访问它们,而不能通过 foo 访问它们).

I partially agree with the airbnb styleguide to not to use wildcard imports, although javascripts wildcard imports do not suffer from the same diseases as for example pythons or javas wildcard imports, namely it does not pollute the scope with variable names defined in other modules (you can only access them by moduleB.foo, not foo when using import * as moduleB from ...).

关于测试的文章:我有点理解这些担忧,但我看不到那里无法解决的问题.您可以使用一些自定义模块加载器来模拟导入本身(自定义 amd 模块加载器实际上是 15 行代码),因此您不必弄乱被测试模块的本地范围.

About the article on testing: I kindof understand the concerns, but I see nothing that cannot be solved there. You can mock the imports themselves with some custom module loader (a custom amd module loader is literally 15 lines of code), so you dont have to mess with the local scope of the tested module.

这篇关于通配符或星号 (*) 与命名或选择性导入 es6 javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆