Sub topic 1
How ES Modules Load: A Quick Recap
The rest of this tutorial covers JSON modules: how they load, what they export, how they are cached, and why some imports fail. All of that depends on how the JavaScript module system loads code. This chapter goes back over that loading process. It focuses on the parts that matter later: how a specifier becomes a URL, the module map, the three loading phases, and when errors happen.
Prerequisites
This chapter assumes you already know the following:
- ES module syntax. You have written
importandexportstatements, including default and named exports. - JSON syntax and
JSON.parse. You know what valid JSON looks like and how to turn a JSON string into an object. - Promises and async/await. You can read code that awaits a Promise.
- Running JavaScript. You can run a script in Node.js (version 18 or later is fine for this chapter) or load a
<script type="module">in a browser.
If any of these are unfamiliar, review them first. Everything below builds on them.
Setting Up a Runnable Example
The examples in this chapter run in Node.js. Create a folder with a package.json that marks .js files as ES modules:
{
"name": "esm-recap",
"type": "module"
}Each example below lists its files. Put them in the same folder and run node main.js.
From Specifier to Module
Every import statement contains a module specifier, the string after from. In import { add } from "./math.js", the specifier is "./math.js".
The host turns the specifier into an absolute URL. The host is the environment running the code, such as a browser or Node.js. This step is called resolution. Relative specifiers resolve against the URL of the importing module. If main.js lives at file:///app/main.js, then "./math.js" resolves to file:///app/math.js.
The resolved URL is the module's identity. The language specification does not say how a URL becomes source code. Fetching and interpreting the bytes is left to the host. This matters for JSON modules:
- A browser fetches the URL over HTTP and decides what kind of resource it got from the
Content-Typeheader (the MIME type). - Node.js reads the file from disk and mostly decides from the file extension.
So the host decides whether a resource is JavaScript or something else, and it may decide based on information the importing code never sees. Keep this in mind. A later chapter explains why with { type: "json" } exists to close exactly this gap.
The Three Phases of Loading
ES modules load in three separate phases. The whole graph of modules finishes one phase before any module starts the next.
| Phase | What happens | Typical errors |
|---|---|---|
| Construction (fetch and parse) | Resolve specifiers, fetch each file, parse it into a module record, find its imports, repeat for dependencies | Network or file-not-found errors, syntax errors |
| Linking (instantiation) | Create bindings for every export and wire each import to the matching export | `SyntaxError` for a missing named export |
| Evaluation | Run each module's top-level code once, dependencies first | Any runtime error thrown by top-level code |
Construction
During construction the loader finds every module in the graph. It parses each module only to read its static import and export declarations. No code runs yet. Static imports can be found without running anything, which is why import declarations must appear at the top level and their specifiers must be string literals.
A module record is the parsed result. It stores the module's source, its list of requested modules, and its list of exports.
Linking
Linking creates a slot in memory for every exported name and points every import at the right slot. These connections are live bindings. An import does not copy a value. It is a read-only view of the exporter's variable.
Linking is also where missing exports are caught. If you import a name the target module does not export, the whole graph fails before any code runs.
Evaluation
Evaluation runs each module's top-level code exactly once. The order is depth-first and post-order: a module's dependencies run before the module itself, in the order its import statements appear.
Seeing the Phases in Action
Evaluation order
Create three files:
// a.js
console.log("evaluating a");
export const a = "A";// b.js
console.log("evaluating b");
export const b = "B";// main.js
console.log("evaluating main");
import { a } from "./a.js";
import { b } from "./b.js";
console.log(a, b);Running node main.js prints:
evaluating a
evaluating b
evaluating main
A Bmain.js logs first in the source, but its code runs last. Import declarations are hoisted. The loader handles them during construction and linking, and main.js only runs after both of its dependencies have finished.
Live bindings and read-only imports
// counter.js
export let count = 0;
export function increment() {
count += 1;
}// main.js
import { count, increment } from "./counter.js";
console.log(count); // 0
increment();
console.log(count); // 1
try {
count = 10;
} catch (err) {
console.log(err.name); // TypeError
}The second console.log prints 1 because count is a live binding to the variable in counter.js. Assigning to an imported binding throws a TypeError. Only the exporting module can change its own variables.
A link-time failure
// math.js
export function add(x, y) {
return x + y;
}// main.js
console.log("this never prints");
import { add, subtract } from "./math.js";
console.log(add(1, 2));Node.js reports an error like this:
SyntaxError: The requested module './math.js' does not provide an export named 'subtract'The first console.log never runs. The error happens during linking, before evaluation starts for any module. It is reported as a SyntaxError even though both files parse correctly. You will meet this exact error again when you try named imports from a JSON module.
The Module Map: One Instance per Module
The host keeps a module map, a cache of modules keyed by resolved URL. Before fetching a module, the loader checks the map. If the module is already there, the loader reuses it. In browsers the key also includes the module type, so a JSON module and a JavaScript module at the same URL are tracked separately.
This has two effects:
- A module is fetched, parsed, and evaluated at most once per graph, however many files import it.
- Every importer sees the same module instance and the same exported values.
// shared.js
console.log("evaluating shared");
export const state = { hits: 0 };// first.js
import { state } from "./shared.js";
state.hits += 1;// main.js
import "./first.js";
import { state } from "./shared.js";
console.log(state.hits); // 1"evaluating shared" prints once. main.js sees hits as 1 because first.js changed the same object. The binding state is read-only, but the object it points to can still be mutated. A later chapter shows the same behavior with JSON modules, where it surprises people more often.
Static and Dynamic Imports
A static import declaration is handled during construction, so its target must be known before any code runs. Dynamic import() is an expression. It runs during evaluation, takes any string, and returns a Promise for the module's namespace object. The namespace object has one property per export, and the default export appears as default.
// main.js
const name = "math";
const mod = await import(`./${name}.js`);
console.log(mod.add(2, 3)); // 5
console.log(Object.keys(mod)); // [ 'add' ]Dynamic import still goes through construction, linking, and evaluation, this time for the new subgraph. It also uses the module map, so importing an already loaded module resolves to the cached instance. Top-level await works here because main.js is a module.
What Carries Forward
| Concept | Why it matters for JSON modules |
|---|---|
| The host interprets fetched bytes | The `type` attribute tells the host what you expect to receive |
| Link-time export checking | Named imports from JSON fail before code runs |
| Module map caching | A JSON file is parsed once, and its object is shared |
| Namespace objects | Dynamic JSON imports expose data under `default` |
| Dynamic import rejects on error | Lets you handle missing or invalid JSON at runtime |
Exercise
A project has main.js with import "./x.js"; import "./y.js";. Both x.js and y.js contain import "./z.js";. Each file starts with a console.log of its own name. What does node main.js print, and why does z appear only once?
Show answer
It prints z, x, y, main. Evaluation is depth-first and post-order. x.js runs only after its dependency z.js, then y.js runs, and main.js runs last. z.js is already in the module map when y.js imports it, so it is not evaluated again.
Exercise
A file begins with console.log("start"); and then has import { missing } from "./lib.js";, where lib.js does not export missing. Does "start" print? Name the phase in which the error occurs.
Show answer
No. The error is a SyntaxError raised during linking, which finishes for the whole graph before any module is evaluated. Import declarations are hoisted, so the console.log line never runs.
Exercise
Module counter.js exports let count = 0. An importer runs count++. What happens, and how should the importer change the value instead?
Show answer
A TypeError is thrown because imported bindings are read-only views of the exporter's variable. The exporting module must provide a function, such as increment(), that changes count from inside counter.js.