What is the defined execution order of ES6 imports?

Max picture Max · Feb 22, 2016 · Viewed 11.8k times · Source

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?

Answer

McMath picture McMath · Feb 22, 2016

JavaScript modules are evaluated asynchronously. However, all imports are evaluated prior to the body of module doing the importing. This makes JavaScript modules different from CommonJS modules in Node or <script> tags without the async attribute. JavaScript modules are closer to the AMD spec when it comes to how they are loaded. For more detail, see section 16.6.1 of Exploring ES6 by Axel Rauschmayer.

Thus, in the example provided by the questioner, the order of execution cannot be guaranteed. There are two possible outcomes. We might see this in the console:

one
two
three

Or we 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 definitely be executed prior to the body of the module that imports them, so "three" is guaranteed to be logged last.

The asynchronicity of modules can be observed when using top-level await statements (now implemented in Chrome). For example, suppose we modify the questioner's example slightly:

// main.js
import './one.js';
import './two.js';
console.log('three');

// one.js
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('one');

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

When we run main.js, we see the following in the console (with timestamps added for illustration):

[0s] two
[1s] one
[1s] three