ES6在多个位置导入文件,为什么文件一次加载? [英] ES6 import a file in multiple place, why the file loads once?
本文介绍了ES6在多个位置导入文件,为什么文件一次加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果有一个名为common.js
的公共文件,还有其他文件,例如a.js
,b.js
...
If there has a common file named common.js
, and others such as 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
加载到内存中.
First, a.js
runs and load the common.js
into memory.
然后,b.js
由引擎运行.
-
common.js
是否会再次加载或使用内存中现有的common.js
? - 如果
common.js
是由其他xx.js
脚本更新的,import
的行为将如何?
- Does the
common.js
will load again or use the existingcommon.js
in the memory? - If
common.js
was updated by otherxx.js
script, how will theimport
behave?
推荐答案
我假设您正在使用Node.js,因此import
在编译后将变成require
语句.
I'm assuming you are using Node.js so the import
will turn into require
statements after transpiling.
从文档中
模块在第一次加载后被缓存.这意味着(除其他事项外)每次对
require('foo')
的调用都将返回完全相同的对象,如果它可以解析为相同的文件.
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.
要明确回答您的问题:
- 模块已缓存,因此您要更改同一对象
- 它将打印最后分配的值
- 例如
changed
如果执行了a.js
- 如果仅执行
b.js
,则它将打印initial
- 例如
- The module is cached so you are changing the same object
- It will print the the last value assigned
- for example
changed
ifa.js
was executed - if only
b.js
is executed, then it will printinitial
- for example
在线试用此处.
这篇关于ES6在多个位置导入文件,为什么文件一次加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文