ES6进口的定义执行顺序是什么

ES6进口的定义执行顺序是什么

本文介绍了ES6进口的定义执行顺序是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试在互联网上搜索导入模块的执行顺序。例如,假设我有以下代码:

  c>3保证最后被记录。



也就是说,是否遵循这方面的原始规格。



更新



在评论,我决定更仔细地研究一下。尽管有上述资料,但在模块加载是异步的(尽管不可否认,作为英语母语者,我发现这个规范有点难以阅读)。如果是这种情况,则执行导入的顺序将取决于实现。也就是说,同样的结论是:你不能指望你的进口是以任何特定的顺序执行。


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?

解决方案

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.

这篇关于ES6进口的定义执行顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:05