直接导入ES6模块元素或导入后解构const赋值? [英] Import ES6 module elements directly or destructure const assignment following the import?

查看:99
本文介绍了直接导入ES6模块元素或导入后解构const赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6模块有点新,发现自己在以下两种模式之间徘徊......

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

模式#1 - 解析 import

Pattern #1 - Destructuring on import

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

模式#2 - 解析 const

Pattern #2 - Destructuring on const

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

我喜欢模式#1,因为它简洁,但我也喜欢模式#2,因为它似乎更多明确。

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?

推荐答案

在ES6中,导入绑定到变量(而不是值)。这意味着如果导出模块更改了导出的变量,则更新的值将反映在导入它的所有模块中。

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);

假设你这样导入它:

main1.js

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

输出为:

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);

此计划的输出为:

1
1

这种差异可能是你想要记住的事情。

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

这篇关于直接导入ES6模块元素或导入后解构const赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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