如果有一个名为common.js
的公共(public)文件,以及其他如a.js
、b.js
...
common.js
const Common = { property: 'initial' }
export { Common };
a.js
import { Common } from 'common.js';
Common.property = 'changed';
b.js
import { Common } from 'common.js';
console.log(Common.property);
首先,a.js
运行并将 common.js
加载到内存中。
然后,b.js
由引擎运行。
common.js
会再次加载还是使用内存中已有的common.js
?- 如果
common.js
被其他xx.js
脚本更新,import
将如何表现?
最佳答案
我假设您使用的是 Node.js,因此 import
将在转译后变成 require
语句。
来自文档:
Modules are cached after the first time they are loaded. This means (among other things) that every call to
require('foo')
will get exactly the same object returned, if it would resolve to the same file.
明确回答您的问题:
- 模块已缓存,因此您正在更改同一个对象
- 它将打印最后分配的值
- 例如
改变
如果a.js
被执行 - 如果只执行
b.js
,那么它会打印initial
- 例如
在线试用 here .
关于javascript - ES6 在多个地方导入一个文件,为什么文件只加载一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45638740/