What you'll learn: By the end of this lesson you will be able to explain what a JavaScript engine does with an
importbefore any of your code runs, predict the order module bodies execute in (including inside a cycle), say why an import is a live read-only view and not a copy, and choose the TypeScript settings that keep a large code base type-checked, transpilable file by file, and honest about what exists at run time.
Think of a restaurant kitchen. Each station has a card listing the stations it needs ingredients from. Before service starts, the head chef reads every card, makes sure each station's shelves are labelled, and only then lets the stations cook, a station only after the ones it depends on. A module system is that card file. TypeScript is the health inspector who reads the same cards and checks the labels, but who leaves before service starts: nothing the inspector knows is in the kitchen while the food is being cooked.
This lesson gives the working model of both. How a bundler cuts the graph into files is in Code Splitting, Lazy Loading and Tree Shaking, and how to keep folders from importing each other's internals is in Module Boundaries and Public APIs. Here the focus is what the language and the compiler guarantee. It builds on HTML, CSS and JavaScript Architecture.
The core idea
- A module is a file with a static list of imports and exports. The host can read that list without running the code, so it knows the whole graph before anything executes.
- Loading is three steps: build the graph (find and parse every file), link it (create the bindings), then evaluate it (run the bodies). MDN names these as the host's job: "Module graph building, linking, and evaluation, including cycle detection."
- Each module body runs once, dependencies first. Importing a module twice gives you the same instance.
- An import is a live, read-only view of an export, not a copy of its value.
- TypeScript is a separate pass that gets erased. It checks types and then its annotations vanish, so a type error does not stop a file from running unless your pipeline stops it.
Versions at the time of writing: the lab ran on Node 26.13.1 with TypeScript 7.0.2 in the type-check step. Option names below come from the TypeScript documentation pages listed at the end.
How a module graph is loaded
Figure 1. A graph where two modules share a dependency
How to read this: arrows point from importer to imported. The body of a module runs after the bodies of everything it imports, and shared.ts runs once although two files import it.
Figure 2. The three steps the host performs
How to read this: nothing in your code has run until the last arrow. The first two steps are why a misspelled import name fails before any line of the module executes.
Illustration 1, the minimal example: order and sharing
The lab has a folder of real .ts files, each of which records a line when its body runs. main.ts imports a.ts then b.ts, and both import shared.ts:
Expected output, captured from a real run (the evaluation-order scenario):
=== evaluation-order
lesson: Dependencies first, each module once
entry: order/main.ts
1. evaluate order/shared.ts
2. evaluate order/a.ts
3. evaluate order/b.ts
4. evaluate order/main.ts
loaded before the entry body, as the import statements predict: order/shared.ts, order/a.ts, order/b.ts (matches)
That is Figure 1 with real files. MDN's page on import states the rule: "the imported modules' side effects are produced before the rest of the module's code runs". A module you import twice is not run twice, which is why a module-level const works as a shared singleton inside one page.
Live bindings, not copies
MDN: "The imported bindings are called live bindings because they are updated by the module that exported the binding, but cannot be re-assigned by the importing module." The lab's counter.ts exports let count and a function that adds one. The importer prints the import, a copy it made earlier, and the namespace view; then it tries to assign:
Expected output, captured from a real run (the live-bindings scenario):
=== live-bindings
lesson: An import is a live read-only view, not a copy
entry: live/main.ts
1. evaluate live/counter.ts
2. before: count=0 copy=0
3. after increment(): count=1 copy=0 namespace.count=1
4. assigning to an import: TypeError
The copy stayed at 0 because it is a plain number taken at one moment. This is why a store module can export a let and a setter, and why exporting a snapshot object you later replace is a bug. The writer is always the module that owns the binding.
Cycles: when order stops being obvious
When a imports b and b imports a, one of them has to run first, and it sees the other half-finished. MDN says this directly: "With cyclic imports, an imported module may not have finished evaluating, so an imported binding may still be uninitialized."
Figure 3. What happens in a cycle
How to read this: the cycle is broken at the point where it closes. b runs with a entered but not run.
Illustration 2, the realistic failure: a cycle that works until it does not
In the lab, b.ts calls a function declared in a.ts and then reads a const exported by a.ts:
Expected output, captured from a real run (the cycle scenario):
=== cycle
lesson: A cycle: functions are ready, consts are not yet
entry: cycle/main.ts
1. evaluate cycle/b.ts (body starts)
2. call describeA() during the cycle: describeA is a function declaration
3. read label during the cycle: ReferenceError
4. evaluate cycle/a.ts (body)
5. evaluate cycle/main.ts
loaded before the entry body, as the import statements predict: cycle/b.ts, cycle/a.ts (matches)
cycles found: cycle/a.ts -> cycle/b.ts -> cycle/a.ts
A function declaration is usable because it exists once the module is linked, and the const is in its temporal dead zone until its line runs, which raises a ReferenceError. The consequence is nasty: code that only uses a's exports inside functions called later works, and code that touches them at the top level breaks, so a new import line in another file can turn a working cycle into a crash. The fix is to move the shared piece to a third module that both import, not to reorder the imports.
Loading on demand and talking to CommonJS
import() returns a promise for the module's namespace object, and the lab shows it running a module on first use only; a second call returns the same namespace:
Expected output, captured from a real run (the dynamic-import scenario):
=== dynamic-import
lesson: import() runs a module on demand, once
entry: dynamic/main.ts
1. evaluate dynamic/eager.ts
2. evaluate dynamic/main.ts
3. evaluate dynamic/lazy.ts
4. first import() settled
5. second import() settled; same namespace object: true
loaded before the entry body, as the import statements predict: dynamic/eager.ts (matches)
This is the primitive under route-level code splitting. A static reader of import statements, like the lab's, cannot see a dynamic import, which is also why bundlers have to treat them specially.
Two Node facts matter when libraries mix formats. Importing a CommonJS module from ESM gives you module.exports as the default export ("Named exports may be available, provided by static analysis as a convenience"), and require of an ES module "currently only supports loading synchronous ES modules (that is, ES modules that do not use top-level await)". Which format a .ts or .js file is depends, under TypeScript's module: nodenext, on the nearest package.json "type" field.
TypeScript: a separate pass that is erased
Node's documentation says it plainly: it "will replace TypeScript syntax with whitespace, and no type checking is performed". The lab shows the consequence with a file that has a deliberate type error:
Expected output, captured from a real run (the types-erased scenario):
=== types-erased
lesson: Type annotations do not exist at run time
entry: types/erased.ts
1. typeof n at run time: string
loaded before the entry body, as the import statements predict: none (matches)
The variable was declared number and holds a string. Only tsc knew. A pipeline needs a step that runs the compiler and fails the build, shown in Figure 4.
Figure 4. Three jobs, three tools
How to read this: the two paths from the source never meet. The type check does not feed the running code, so the gate is what makes a type error matter.
The type modifier and verbatimModuleSyntax
A tool that works on one file at a time cannot know whether Shape is a type, so it needs a hint. TypeScript's verbatimModuleSyntax makes the rule simple: "any imports or exports without a type modifier are left around. Anything that uses the type modifier is dropped entirely." The one subtle case is the inline form, which TypeScript rewrites to import {} from "xyz", so the file is still loaded. Node's documentation says the same: without the type keyword Node "will treat the import as a value import, which will result in a runtime error". The lab shows all three:
Expected output, captured from a real run (the import-type, inline-type and value-import-of-a-type scenarios):
=== import-type
lesson: import type leaves no import behind
entry: types/import-type.ts
1. import type: the other module was not loaded; square.sides=4
loaded before the entry body, as the import statements predict: none (matches)
=== inline-type
lesson: import { type X } keeps the import and its side effects
entry: types/inline-type.ts
1. evaluate types/types-only.ts
2. import { type }: the other module was still loaded; square.sides=4
loaded before the entry body, as the import statements predict: types/types-only.ts (matches)
=== value-import-of-a-type
lesson: Importing a type as a value fails at link time
entry: types/value-import.ts
import() rejected: SyntaxError: The requested module './types-only.ts' does not provide an export named 'Shape'
This is the link step from Figure 2 failing: before any body ran, the loader found that no export named Shape exists. Use import type when you want no trace of the import, and know that import { type X } still loads the file.
The settings that matter at scale
isolatedModules"tells TypeScript to warn you if you write certain code that can't be correctly interpreted by a single-file transpilation process". It does not change emit. Turn it on whenever a tool other thantsctranspiles your files.erasableSyntaxOnlymakes TypeScript error on constructs that have runtime behaviour, such asenumand parameter properties, which Node's type stripping cannot handle.moduleandmoduleResolution.nodenextmodels Node's dual ESM/CJS system and emits either format per file.bundler"attempts to model the module resolution behavior common to most JavaScript bundlers" and is paired withmodule: esnextorpreserve. Pick the one that matches what actually loads the files.paths"does not change the import path in the code emitted by TypeScript". An alias that type-checks can crash at run time unless the bundler or runtime has the same mapping. A published library should not use it.- Project references split a program into pieces, which can "greatly improve build times, enforce logical separation between components"; a referenced project needs
composite, andtsc --buildrebuilds only out-of-date projects in dependency order.
Barrel files and graph size
A barrel is an index.ts that re-exports a folder. It gives a clean public path (see the boundaries lesson), but importing one name loads the barrel and everything the barrel imports, so a barrel over a large folder enlarges the graph for every importer. The code-splitting lesson covers what a bundler can and cannot drop. Keep barrels at feature boundaries, not inside every folder.
Trade-offs
| Choice | Gains | Costs |
|---|---|---|
| Native ESM everywhere | One semantics, live bindings, static analysis | Libraries still shipping CommonJS need interop |
paths aliases |
Short imports | Needs matching config in every tool; not in emit |
| Project references | Faster incremental builds, enforced layers | Extra tsconfig files and a build mode |
verbatimModuleSyntax |
Predictable emit, matches Node | Must write import type correctly |
| Barrel per feature | One public door | Larger graph if overused; cycles are easy to add |
Strict moduleResolution (nodenext) |
Matches what Node does | File extensions required in imports |
Build it: watch the real loader
Goal. Run eight scenarios of real modules on Node's own loader and compare a static prediction with what actually ran.
cd examples/frontend/labs/esm-module-semantics
pnpm test # 22 tests; each scenario runs in a fresh Node process
pnpm typecheck
node src/demo.ts # prints the eight scenarios
This lab is Node, not a browser. Browsers and Node implement the same module language, but fetching, caching and error reporting differ. The static reader in src/graph.ts uses a regular expression, not a parser: it is a teaching aid that only handles the fixtures' import forms.
Break it. In src/fixtures/cycle/b.ts, remove the try. The scenario now rejects with a ReferenceError and the cycle test fails. Restore it, because a cycle that throws is the point of the example, not a defect to leave behind.
In practice: a storefront whose checkout page crashes after a refactor
This is a realistic scenario, not a case history.
The situation
A product and checkout front end has grown to several hundred modules in one tsconfig. A new "free shipping" rule needs the cart total, and a developer imports cart from pricing, which already imports pricing from cart.
Starting architecture
Figure 5. A cycle between pricing and cart
How to read this: the red arrow closes the loop. Whether it breaks depends on what runs at the top level of each file.
Options considered
| Option | Result | Risk |
|---|---|---|
| Reorder the imports until it works | Passes today | Fragile; the next import can flip it |
Pass the cart total into pricing as an argument |
No import needed | A small signature change |
| Move the shared rule to a third module | Breaks the cycle | One more file |
The decision
Pass the total as a parameter, so pricing stays pure and does not import cart.
Rollout and verification
Add an import-cycle check to CI, using a graph tool as described in the boundaries lesson. Add one test that imports checkout and fails on a thrown ReferenceError.
The 2 a.m. failure
A later change adds a top-level const FREE_SHIPPING = cartLimit * 2 in pricing, reading a constant exported by cart. If pricing happens to run first, that read hits the temporal dead zone and the checkout bundle throws on load. The stack trace names pricing, not the change that caused it. The rollback is the cycle fix above; the lasting protection is the CI cycle check.
Architect's notes
- Ask of every new import: does it add an edge that closes a loop?
- Put the type check in CI as a required gate, not as an editor hint.
- Choose
moduleandmoduleResolutionby what loads your files, then stop changing them. - Keep shared singletons in modules with no import of their consumers.
Common mistakes
- Assuming a type error blocks the build when only a transpiler runs.
- Importing a type without
typeunderverbatimModuleSyntax. - Relying on
pathsin emitted code or in a library. - Reading an imported
constat the top level inside a cycle. - Replacing an exported object instead of mutating it, then wondering why importers kept the old one.
Key takeaways
- Imports are read before code runs; bodies run dependencies first and once.
- An import is a live read-only view; only the owner can reassign it.
- In a cycle, function declarations are ready and
constbindings may not be. - TypeScript types are erased; the type check is a separate gate.
import typeleaves nothing behind;import { type X }still loads the module.pathschanges only what the compiler understands, not what runs.
Practice exercises
Exercise 1, easy (20 minutes). Run the lab and write down, before reading the output, the order of the lines for the cycle scenario. Then compare.
Exercise 2, intermediate (45 minutes). Add a fixture where a.ts exports a class and b.ts uses it at the top level inside a cycle, and record what Node does.
Exercise 3, intermediate (60 minutes). Take one module in your own app that sits in a cycle, remove the cycle by moving the shared code to a third file, and add a CI check that fails on a new cycle.
Related reading
- Module Boundaries and Public APIs: keeping folders apart, barrels and cycle checks.
- Code Splitting, Lazy Loading and Tree Shaking: what a bundler does with the graph.
- Monorepos and Shared Libraries: package boundaries across projects.
- Event Loop and the Main Thread: why top-level
awaitand long module bodies block.
Official documentation
- import (MDN): live bindings, hoisting, side-effect imports.
- JavaScript modules guide (MDN): strict mode, read-only views, dynamic
import(). - Modules reference (TypeScript):
module,moduleResolution, type-only imports,paths. - TSConfig reference (TypeScript):
verbatimModuleSyntax,isolatedModules,erasableSyntaxOnly. - Project references (TypeScript):
compositeandtsc --build. - Modules: TypeScript (Node.js): type stripping and the
typekeyword; also ECMAScript modules.