ES6进口的定义执行顺序是什么? [英] What is the defined execution order of ES6 imports?

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

问题描述

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

  importone
importtwo
console.log(three);

其中 one.js two.js 定义如下:

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

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

控制台输出保证为:

  one 
two
three

还是未定义?

解决方案

异步执行导入的ES6模块。但是,所有导入都在脚本执行导入之前执行。这使得ES6模块与例如 Node.js模块 < script> 标签没有 async 属性。 ES6模块更接近于 AMD规范,当涉及到加载。有关详细信息,请参阅探索的第16.6.1节由Axel Rauschmayer提供的ES6



所以,在上面提供的例子中,执行顺序是无法保证的。有两个可能的结果。您可能会看到:

  one 
two
three

或者您可能会看到:

  
一个

换句话说,两个导入的模块可以执行 console.log()任何命令的调用;它们是相对于彼此异步的。但是,它们一定会在导入脚本之前执行,所以 c>3保证最后被记录。



也就是说,没有现代的浏览器实现ES6模块。我不知道透明胶片如 Babel 是否遵循这方面的原始规格。



更新



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


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进口的定义执行顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆