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

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

问题描述

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

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

导入*作为Foo来自'./foo';

VS:

import {bar,bar2,bar3}来自'./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提供的代码消除,或者使用树状抖动的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通配符导入不会遇到与pythons或javas通配符导入相同的疾病,即它不会污染范围,而是使用其他mo定义的变量名称dules(你只能通过 moduleB.foo 访问它们,而不是 foo 使用 import *作为moduleB来自...... )。

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.

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

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