Sub topic 1
Recap: Static Imports and the Module Graph
import() and top-level await both change when modules load and run. Before looking at them, it helps to be clear about what happens by default. This chapter reviews how static import declarations work, how the runtime builds a module graph from them, and in what order that graph is evaluated. The last section lists the limits of static imports, which are the problems the rest of this tutorial addresses.
Prerequisites
This chapter assumes you already know:
- ES module syntax:
import,export,export default, and named exports. - Promises and
async/await, which later chapters rely on. - How to run an ES module, either with
node file.mjsor in a browser with<script type="module">. The next chapter covers these module contexts in detail. - What npm packages are and how a bare name such as
'lodash'refers to one.
All examples here use .mjs files so that Node.js treats them as ES modules with no extra configuration. Put the files in one folder and run the entry file with node.
What Makes an Import "Static"
A static import is an import declaration written at the top level of a module:
import { add } from './math.mjs';
import format from './format.mjs';
import * as utils from './utils.mjs';The word "static" means the runtime can learn everything about the import by parsing the source text, without running any code. Three rules make this possible:
- Top level only. An
importdeclaration cannot appear inside a function, anifblock, or atryblock. Putting one there is aSyntaxError. - Literal specifier. The module specifier (the string after
from) must be a plain string literal. You cannot writefrom './' + name. - Fixed names. The imported names are listed in the source, so the runtime knows which exports each module expects from each dependency.
Because of these rules, the engine can read a file, find every dependency, and check that every requested export exists before any statement in the program runs. Bundlers, linters, and tree-shaking tools rely on the same property.
The Module Graph
Each module names its dependencies, and those dependencies name theirs, so the full set of modules forms a directed graph. The entry module is the root. An edge from A to B means "A imports B."
Notice that d.mjs appears once even though two modules import it. A module is identified by its resolved URL (or resolved file path in Node.js). However many importers it has, it gets one module record, one evaluation, and one set of exports. Every importer shares that single instance.
The Three Phases of Loading
The runtime processes the graph in three phases. Every module in the graph finishes one phase before any module starts the next.
| Phase | What happens | Can user code run? |
|---|---|---|
| Construction | Resolve each specifier, fetch the file, parse it, find its imports, repeat for each dependency | No |
| Linking | Create bindings for every export and connect each import to the export it names | No |
| Evaluation | Run each module's top-level code, dependencies first | Yes |
Construction
Starting at the entry module, the loader resolves each specifier to a full URL or path, fetches the file, and parses it. Parsing reveals the module's own import declarations, and the loader repeats the process for each one. In a browser, these fetches can happen in parallel. A missing file or a syntax error anywhere in the graph stops the whole load.
Linking
The runtime sets aside memory for every exported binding and points each import at the matching export. If a module asks for a name its dependency does not export, linking fails. Here is a two-file example:
// math.mjs
export function add(a, b) {
return a + b;
}// main.mjs
console.log('main started');
import { add, subtract } from './math.mjs';
console.log(add(1, 2));Running node main.mjs prints no main started line. You get an error similar to this:
SyntaxError: The requested module './math.mjs' does not provide an export named 'subtract'The error appears before evaluation, so not even the first console.log runs. This is the all-or-nothing behavior of static imports.
Evaluation
After linking succeeds, the runtime runs each module's top-level code exactly once. The order is a depth-first, post-order walk: a module runs only after all of its dependencies have run, and siblings run in the order their import declarations appear.
Here are four files matching the diagram above:
// d.mjs
console.log('d');// b.mjs
import './d.mjs';
console.log('b');// c.mjs
import './d.mjs';
console.log('c');// main.mjs
import './b.mjs';
import './c.mjs';
console.log('main');Running node main.mjs prints:
d
b
c
maind.mjs runs first because b.mjs needs it. It does not run again when c.mjs imports it, because the module instance is already evaluated and cached. Evaluation here is fully synchronous. Once it begins, the whole graph runs to completion in one pass. Top-level await, covered later, is the feature that changes this.
Hoisting and Live Bindings
Two more behaviors of static imports come up again in later chapters.
Imports are hoisted
Import declarations take effect before any code in the module runs, wherever they appear in the file. This works:
// main.mjs
console.log(add(2, 3)); // 5
import { add } from './math.mjs';Putting imports at the top of the file is still the normal style, but the engine does not depend on it.
Imports are live, read-only views
An imported name is not a copy of a value. It is a live view of the exporting module's variable. If the exporter changes the variable, importers see the new value. Importers cannot assign to it themselves.
// counter.mjs
export let count = 0;
export function increment() {
count += 1;
}// main.mjs
import { count, increment } from './counter.mjs';
console.log(count); // 0
increment();
console.log(count); // 1
try {
count = 10;
} catch (err) {
console.log(err.name); // TypeError
}The live connection is made during linking, which is why linking happens before evaluation. The module namespace object you get from import() follows the same rules, as a later chapter shows.
Where Static Imports Fall Short
The same rules that make static imports easy to analyze also limit them:
- Everything loads up front. Every module in the graph is fetched and evaluated before the entry module runs, even code for a dialog the user may never open. This adds to startup time.
- No conditions. You cannot import a module only on some platforms, or only when a feature flag is set, because
importcannot sit inside anif. - No computed specifiers. You cannot pick a locale file from a variable such as `
./locales/${lang}.js`. - No recovery. If one dependency is missing or fails to parse, the whole program fails. There is no
try/catcharound a static import. - No waiting. Evaluation is synchronous, so a module cannot finish loading configuration over the network before its exports are used.
The import() expression handles the first four by loading modules at runtime and returning a promise. Top-level await handles the last by letting a module pause its own evaluation. The rest of this tutorial covers both, but the construction, linking, and evaluation steps from this chapter still happen underneath each of them.
Exercises
Exercise
An entry module main.mjs contains import './x.mjs'; import './y.mjs'; console.log('main');. x.mjs contains import './y.mjs'; console.log('x');. y.mjs contains console.log('y');. What does node main.mjs print, and why does y appear only once?
Show answer
It prints y, x, main. Evaluation is depth-first post-order: main's first dependency is x, and x's dependency y runs before x. When main then reaches its own import of y, that module is already evaluated and cached under its resolved path, so it does not run again.
Exercise
A module's first line is console.log('starting'); and a later line is import { helper } from './tools.mjs';, but tools.mjs has no export named helper. Does "starting" get printed? Explain using the loading phases.
Show answer
No. The missing export is detected during linking, which finishes for the whole graph before evaluation starts. Since no module begins evaluating, the console.log never runs, and the program fails with a SyntaxError saying the requested module does not provide an export named 'helper'.
Exercise
settings.mjs exports let theme = 'light' and a function setTheme(t) that reassigns theme. main.mjs imports both, calls setTheme('dark'), then logs theme. What is logged, and what happens if main.mjs instead runs theme = 'dark'?
Show answer
It logs 'dark', because imported names are live bindings to the exporter's variable. Assigning theme = 'dark' directly in main.mjs throws a TypeError, because imported bindings are read-only in the importing module.
Exercise
Name two requirements that a static import cannot meet but that a later chapter's import() expression can.
Show answer
Any two of: loading a module only under a runtime condition, building the specifier from a variable, deferring the load until it is needed to cut startup cost, and catching a load failure to use a fallback.