Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

javascript - What is the defined execution order of ES6 imports?

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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...