What is the defined execution order of ES6 imports?

早过忘川 提交于 2019-11-26 14:07:56

问题


I've tried searching the internet for the execution order of imported modules. For instance, let's say I have the following code:

import "one"
import "two"
console.log("three");

Where one.js and two.js are defined as follows:

// one.js
console.log("one");

// two.js
console.log("two");

Is the console output guaranteed to be:

one
two
three

Or is it undefined?


回答1:


Imported ES6 modules are executed asynchronously. However, all imports are executed prior to the script doing the importing. This makes ES6 modules different from, for example, Node.js modules or <script> tags without the async attribute. ES6 modules are closer to the AMD specification when it comes to loading. For more detail, see section 16.6.1 of Exploring ES6 by Axel Rauschmayer.

So, in the example you provide above, the order of execution cannot be guaranteed. There are two possible outcomes. You might see this:

one
two
three

Or you might see this:

two
one
three

In other words, the two imported modules could execute their console.log() calls in any order; they are asynchronous with respect to one another. But they will certainly be executed prior to the script that imports them, so "three" is guaranteed to be logged last.

That said, no modern browser implements ES6 modules. I don't know if transpilers such as Babel follow the original specification in this respect.

Update

In light @BenjaminGruenbaum's comments below, I decided to look into this more closely. Despite the source above, I could not find it clearly stated in the specification itself that module loading is asynchronous (although admittedly, as a native English speaker, I find the spec a bit difficult to read). If that is the case, then the order in which imports are executed will be implementation-dependent. That said, the same conclusion holds: you cannot count on your imports being executed in any particular order.



来源:https://stackoverflow.com/questions/35551366/what-is-the-defined-execution-order-of-es6-imports

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