...

/

Module Loading in Depth

Module Loading in Depth

Learn loading phases and read-only live bindings in ESM.

To understand how ESM actually works and how it can deal effectively with circular dependencies, we have to deep dive a little bit deeper into how JavaScript code is parsed and evaluated when using ES modules.

In this section, we’ll learn how ECMAScript modules are loaded. We’ll also present the idea of read-only live bindings. Finally, we’ll discuss an example with circular dependencies.

Loading phases

The goal of the interpreter is to build a graph of all the necessary modules, a dependency graph.

Note: In generic terms, a dependency graph can be defined as a directed graph representing the dependencies of a group of objects. In the context of this section, when we refer to a dependency graph, we want to indicate the dependency relationship between ECMAScript modules. As we’ll see, using a dependency graph allows us to determine the order in which all the necessary modules should be loaded in a given project.

Essentially, the dependency graph is needed by the interpreter to figure out how modules depend on each other and in what order the code needs to be executed. When the node interpreter is launched, it gets passed some code to execute, generally in the form of a JavaScript file. This file is the starting point for the dependency resolution, and it’s called the entry point. From the entry point, the interpreter will find and follow all the import statements recursively in a depth-first manner, until all the necessary code is explored and then evaluated.

More specifically, this process happens in three separate phases:

  • Phase 1—Construction (or parsing): Find all the imports and recursively load the content of every module from the respective file.

  • Phase 2—Instantiation: For every exported entity, keep a named reference in memory, but don’t assign any value just yet. Also, references are created for all the import and export statements tracking the dependency relationship between them ( ...