Import ES6 module elements directly or destructure const assignment following the import? [closed]

ⅰ亾dé卋堺 提交于 2019-12-06 09:22:37

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.

The first one is not destructuring, it's importing named exports into the module scope. The second one does import the module namespace object under the name myFuncs and then destructures it.

The major difference is that in the second pattern you've got constants, not direct references to the exported bindings (which might change). This is important e.g. for circular dependencies.

A minor difference is the additional identifier myFuncs, which is rather useless. It does however give you access to all exports of the module, which is important for tree-shaking - if you explicitly import only parts of a module, a bundler might produce smaller results.

Are there good reasons to use one over the other?

Absolutely - the first pattern is simpler, shorter, works correctly in edge cases, and can be better optimised.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!