Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
Max Avatar asked Feb 22 '16 10:02

Max


People also ask

Can I use ES6 imports?

Importing can be done in various ways: Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error.

What is import and export in ES6?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.

Does import order matter typescript?

Import order does not matter. If a module relies on other modules, it needs to import them itself.

How do JavaScript imports work?

Javascript import statement is used to import bindings that are exported by another module. Using import, the code is easier to manage when it is small and bite-size chunks. This is the thinking behind keeping functions to only one task or having files contain only a few or one component at a time.


Video Answer


2 Answers

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 

Update as of ES2020

Per petamoriken's answer, it looks like evaluation order is guaranteed for non-async modules as of ES2020. So, if you know none of the modules you're importing contain top-level await statements, they will be executed in the order in which they are imported. In the case of the questioner's example, the console output will always be:

one two three 
like image 184
McMath Avatar answered Sep 21 '22 12:09

McMath


According to the latest specification InnerModuleEvaluation, the order of module.ExecuteModule() is guaranteed since [[RequestedModules]] is an ordered list of source code occurrences.

// 16.2.1.5.2.1 rough sketch function InnerModuleEvaluation(module, stack, index) {    // ...    // 8   module.[[PendingAsyncDependencies]] = 0;    // ...    // 11: resolve dependencies (source code occurrences order)   for (required of module.[[RequestedModules]]) {     let requiredModule = HostResolveImportedModule(module, required);     // **recursive**     InnerModuleEvaluation(requiredModule, stack, index);      // ...      if (requiredModule.[[AsyncEvaluation]]) {       ++module.[[PendingAsyncDependencies]];     }   }    // 12: execute   if (module.[[PendingAsyncDependencies]] > 0 || module.[[HasTLA]]) {     module.[[AsyncEvaluation]] = true;     if (module.[[PendingAsyncDependencies]] === 0) {       ExecuteAsyncModule(module);     }   } else {     module.ExecuteModule();   }    // ...  } 

The console output is always as follows:

one two three 
like image 29
petamoriken Avatar answered Sep 20 '22 12:09

petamoriken