在 ES6 的 `import` 语法中,模块是如何准确计算的? [英] In the `import` syntax of ES6, how is a module evaluated exactly?
问题描述
假设我们有四个模块,A
、B
、C
和 D
Let's say we have four modules, A
, B
,C
and D
在模块A
中:
console.log("A evaluated")
function AClass {
console.log("A constructor")
}
var aObj = new AClass()
export default aObj;
在模块B
中:
import aObj from A
export default "B"
在 C
模块中:
import aObj from A
export default "C"
在 D
模块中:
import b from B
import c from C
import aObj from A
那么当模块D
被求值时,A求值
和A构造函数
会在控制台打印多少次?
So when module D
is evaluated, how many times will the A evaluated
and A constructor
be printed in the console?
此行为是否在 ES6 标准中描述?如果我希望一个模块无论直接或间接导入多少次都只评估一次,我该怎么办?有没有人对此有任何想法?
Is this behavior described in ES6 standard? What should I do if I want a module to be evaluated ONLY ONCE no matter how many times is imported directly or indirectly? Does anyone have any ideas about this?
推荐答案
D
模块执行时,控制台会打印此信息:
When the D
module is executed, the console will print this message:
A evaluated
A constructor
这意味着 A
模块只被评估一次,即使它被其他模块多次导入.
Which means that the A
module was evaluated only once, even if it was imported multiple times by other modules.
ES6 模块
的评估规则与commonjs
格式相同:
The evaluation rules for ES6 modules
is the same as for commonjs
format:
- 模块是一段代码,一旦加载就会执行.这意味着如果一个模块没有包含在主包中,它将不会被评估
- 模块是单例的.如果一个模块被多次导入,它只存在一个
instance
并且在加载时只评估一次
- A module is a piece of code that is executed once it is loaded. It means that if a module is not included in the main bundle, it will not be evaluated
- Modules are singletons. If a module is imported multiple times, only a single
instance
of it exists and it is evaluated only once at load
描述了导入相同模块实例的行为HostResolveImportedModule 部分.
它提到:
The behaviour of importing the same instance of the module is described HostResolveImportedModule section of the ECMAScript 6 specification.
It mentions:
这个操作(导入操作)如果正常完成就必须是幂等的.每一次它使用特定的引用模块调用,说明符对 (import from as参数它必须返回相同的模块记录实例.
This operation (import operation) must be idempotent if it completes normally. Each time it is called with a specific referencingModule, specifier pair (import <a> from <source>) as arguments it must return the same Module Record instance.
模块单次评估的行为在ModuleEvaluation,第 4 点和第 5 点使用 Evaluated
布尔标志.
每个模块都有 Evaluated
标志,确保只对模块代码进行一次评估.
The behaviour of single time evaluation of the module is described in ModuleEvaluation, point 4 and 5 using Evaluated
boolean flag.
Each module has Evaluated
flag which makes sure to evaluate the module code only once.
这篇关于在 ES6 的 `import` 语法中,模块是如何准确计算的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!