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

回眸只為那壹抹淺笑 提交于 2019-12-12 10:04:18

问题


Somewhat new to ES6 modules and find myself torn between the following 2 patterns...

Pattern #1 - Destructuring on import

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

Pattern #2 - Destructuring on const

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

I like the pattern #1 for its brevity, but I also like pattern #2 as it seems more explicit.

Are there good reasons to use one over the other?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/39238697/import-es6-module-elements-directly-or-destructure-const-assignment-following-th

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