Sub topic 12
How Modules Are Linked and Evaluated
This chapter assumes you know how to write named, default, and side-effect-only imports. It also assumes you have seen that imports are live bindings and that you can run modules in a browser or in Node.js. Here we look at what the JavaScript engine does between reading your import statements and running your code. Several behaviors that seem odd at first follow directly from this process:
- Imports run before the rest of the file.
- A module runs only once, however many files import it.
- A typo in an import name stops the whole program before any line executes.
The Three Phases
Classic scripts load and run top to bottom, one file at a time. ES modules work differently. The engine processes the whole dependency graph in three separate phases, and no module code runs until the first two phases have finished for every module in the graph.
Phase 1: Construction
The engine starts with the entry module. It resolves the specifier to a full URL (a file: URL in Node.js), fetches the file, and parses it. Parsing produces a module record. This internal structure lists the module's imports, its exports, and its compiled code.
Because import and export declarations are static, the parser can read every dependency without running anything. It then resolves, fetches, and parses each dependency in the same way, repeating until it has found every module in the graph. Browsers fetch these files in parallel as they are discovered.
A syntax error in any file, or a file that cannot be fetched, fails the whole graph at this stage.
Phase 2: Linking
Next, the engine creates a module environment for each module. This is the scope that holds its top-level variables. The engine then connects each import to the matching export. An import does not copy a value. It becomes a reference to the exporting module's variable slot, which is why the bindings stay live.
Linking also checks that every imported name exists. If main.js asks for an export that math.js doesn't provide, linking fails with a SyntaxError. No module in the graph has run any code by then.
During linking, function declarations are fully initialized, so their values already exist. Variables declared with let, const, and class are created but left uninitialized. They sit in the temporal dead zone until evaluation reaches their declaration. The chapter on circular dependencies shows where this difference matters.
Phase 3: Evaluation
The engine finally runs each module's top-level code. It walks the graph depth-first and runs each module after all of its dependencies (a post-order traversal). Each module is evaluated exactly once. When the engine reaches a module that has already been evaluated, it skips it.
| Phase | What happens | Typical errors |
|---|---|---|
| Construction | Resolve specifiers, fetch files, parse into module records | `SyntaxError` in a file, 404 or file not found, unresolvable bare specifier |
| Linking | Create module environments, bind imports to exports | `SyntaxError: The requested module does not provide an export named ...` |
| Evaluation | Run top-level code in dependency order | Any runtime error, `ReferenceError` from the temporal dead zone |
Seeing the Evaluation Order
The following three files log a message when they are evaluated.
// a.js
console.log('a evaluating');
export const a = 1;// b.js
import './a.js';
console.log('b evaluating');// main.js
console.log('main evaluating');
import './b.js';
import './a.js';Running node main.js (in a package with "type": "module") prints:
a evaluating
b evaluating
main evaluatingThe output shows three things:
main evaluatingappears last, even though it is the first line ofmain.js. Import declarations are processed before any of the module's code runs, wherever they appear in the file. This is often called import hoisting.a.jsruns beforeb.jsbecauseb.jsdepends on it. Dependencies always evaluate first.a evaluatingappears only once.main.jsimportsa.jstoo, buta.jshas already been evaluated by then, so the engine reuses it.
Modules Are Singletons
Each realm (a browser page, a worker, or a Node.js process) has a module map. This is a cache keyed by the resolved URL of each module. When a specifier resolves to a URL that is already in the map, the engine reuses the existing module instance. It does not create a new one.
As a result, module-level state is shared by every importer.
// registry.js
const handlers = [];
export function register(handler) {
handlers.push(handler);
}
export function count() {
return handlers.length;
}// plugin-a.js
import { register } from './registry.js';
register(() => 'A');// plugin-b.js
import { register } from './lib/../registry.js';
register(() => 'B');// main.js
import './plugin-a.js';
import './plugin-b.js';
import { count } from './registry.js';
console.log(count()); // 2plugin-b.js uses a different specifier, but ./lib/../registry.js resolves to the same URL as ./registry.js. Both plugins therefore share one handlers array.
The URL is the key, so different URLs give different instances, even when they point to the same file.
- Adding a query string, such as
./registry.js?v=2, creates a second instance with its own state. Some test runners and hot-reload tools use this deliberately. - In Node.js, a package installed twice in
node_modules(for example, two versions pulled in by different dependencies) loads as two separate modules. If your code relies on a singleton, such as a shared registry or aninstanceofcheck, it can break without any error message. - Symlinked paths in Node.js are resolved to their real path by default, so a symlink and its target count as one module.
Failures Are Cached Too
The module map also records failures. Suppose a module throws during evaluation. The engine stores that error, and every later attempt to import the module rejects with the same error. The module's code does not run again. In the browser, a page reload is the only way to retry. In Node.js, you need a new process or a different URL. Keep top-level code in a module small and predictable, and move work that can fail into functions that callers invoke and handle themselves.
How This Explains Earlier Behavior
The three phases account for several rules covered in earlier chapters:
- Live bindings exist because linking connects variable slots, not values.
- Read-only imports follow because the importer holds a reference to another module's slot, and only the owning module may write to it.
- Side-effect imports run once because evaluation happens once per module instance.
- Static syntax is required because construction must find every dependency without running code. That is why
importdeclarations can't appear inside anifblock, and whyimport()exists as a separate, runtime mechanism.
Later chapters build on this model. Top-level await changes evaluation so that a module can pause while its importers wait. Circular dependencies show what happens when depth-first evaluation meets a cycle.
Exercise
Given x.js containing console.log('x'); import './y.js'; import './z.js';, y.js containing import './z.js'; console.log('y');, and z.js containing console.log('z');, what does running x.js print, and in what order?
Show answer
It prints z, y, x. Imports are processed before x.js runs. Evaluation is depth-first: y.js is visited first, and its dependency z.js runs before it, printing z and then y. When x.js's own import of z.js comes up, z.js has already been evaluated and is skipped. Finally x.js runs and prints x.
Exercise
main.js imports { helper } from './utils.js', but utils.js only exports helpers. main.js also imports './analytics.js', which sends a network request at its top level. Does the analytics request get sent? Why or why not?
Show answer
No. The missing export is found during linking, which finishes for the whole graph before any module is evaluated. The SyntaxError stops the program before analytics.js's top-level code runs.
Exercise
A test file imports './cache.js' and then './cache.js?fresh'. Both modules have a top-level const store = new Map(). Do the two imports share the same Map?
Show answer
No. The module map is keyed by resolved URL, and the query string makes the second URL different. The engine creates and evaluates a second module instance with its own Map.