Member-only story
JavaScript modules (also known as ES6 modules) are always executed in the same predefined order.
When a module imports other modules, the order in which all the modules are executed is guaranteed to be the same. The order is called left-to-right post-order traversal. Before a module (parent) is executed, all the modules it imports (child modules) are executed. The child modules are executed in the order in which they are specified in the import
statements in the parent module. Let’s make several experiments to demonstrate that.
The complete code of the three tests can be downloaded from Github https://github.com/marianc000/executionOrderModules.
Execution order of child modules
For the first demonstration, I create eight identical child modules a, b, c, d, e, f, g, h. Each of them contains only one line of code — a call to global function recordExecution
with the module url as an argument (modules can retrieve their urls from module-specific import.meta
object).
recordExecution(import.meta.url);
Helper function recordExecution
extracts the module name from the url, and appends it to the end of global array exections
. recordExecution
serves to record a module execution. After all modules are executed, exections
array will contain…