2

对 ES6 模块有些陌生,发现自己在以下两种模式之间徘徊......

模式 #1 - 解构import

import { func1, func2, func3 } from 'my-funcs';

模式 #2 - 解构const

import * as myFuncs from 'my-funcs'; 
const { func1, func2, func3 } = myFuncs;

我喜欢模式#1 的简洁性,但我也喜欢模式#2,因为它看起来更明确。

是否有充分的理由使用其中一种?

4

2 回答 2

3

In ES6, an import is bound to a variable (as opposed to a value). This means that if the exporting module changes the variable it exported, that updated value will be reflected across all modules that imported it.

For example, suppose we have a module which exports a primitive value and then changes it after some unspecified period of time.

myVar.js

export var myVar = "1";
setTimeout(() => {myVar = "2"}, 2000);

Suppose you imported it like so:

main1.js

import { myVar } from './myVar.js';
console.log(myVar);
setTimeout(() => { console.log(myVar); }, 3000);

The output would be:

1
2

However, if you assigned the original value to a variable immediately upon importing it, then the value would be unchanged.

main2.js

import * as MyVar from './myVar.js';
const myVar = MyVar.myVar;
console.log(myVar);
setTimeout(() => { console.log(myVar); }, 3000);

The output of this program would be:

1
1

This difference may be something you want to keep in mind.

于 2016-08-31T00:21:18.437 回答
2

第一个不是解构,它将命名导出导入模块范围。第二个确实在名称下导入模块命名空间对象myFuncs,然后对其进行解构。

主要区别在于,在第二种模式中,您有常量,而不是对导出绑定的直接引用(可能会更改)。这对于循环依赖很重要。

一个小的区别是额外的标识符myFuncs,它相当无用。但是,它确实使您可以访问模块的所有导出,这对于 tree-shaking 很重要 - 如果您仅显式导入模块的一部分,则捆绑器可能会产生较小的结果。

是否有充分的理由使用其中一种?

绝对 - 第一个模式更简单,更短,在边缘情况下正常工作,并且可以更好地优化。

于 2016-08-31T00:24:51.773 回答