In a web build, what is a module graph, and how does a bundler build one starting from an entry point?
answer
- start where the page starts
- imports are the edges
- resolve, load, parse, repeat
- one node per resolved file
- unreached files never ship
basics
~20 sA module graph is every file an app needs, linked by its imports. A bundler starts at each entry, resolves each specifier to one file, parses that file for further imports and repeats until no new file appears.
solid answer
~40 sThe build is given one or more entry modules, usually the scripts the HTML page loads. For each one it reads the file, finds its static `import` declarations and `export … from` re-exports, resolves every specifier to one absolute file and adds that file as a node: once, keyed by its resolved path, however many modules import it. It repeats for every new node, which is why a file nothing imports never reaches the output. A dynamic `import()` with a literal specifier is still followed, but it starts a separately loaded branch of the graph; a specifier marked external is recorded and not followed. A cycle does not stop the walk, because a file already in the graph is not walked twice. The output stage then turns the finished graph into files.
go deeper
Recall the loop: start at the entries, resolve each import to one file, parse it for more imports, repeat. Be able to say why an unimported file is not in the bundle.
Explain that a node is keyed by its resolved path, so many importers share one copy, and walk through what a literal dynamic import, a side-effect import and an external each add to the graph.
Show you can read a resolution failure or an unexpected duplicate as a property of the graph: two resolved paths for one piece of code, a computed specifier the walk skipped, an external nobody provides.
Frame the graph as the contract every later stage depends on, and judge where to cut it: which dependencies a shared library leaves external and which ones each app is expected to bundle.
## What a module graph is A **module graph** is a directed graph in which each **node** is one module (a source file, after resolution) and each **edge** is one import from one module to another. A **bundler** is a build tool that reads that graph and writes a small number of output files the browser can load. Before it can transform, combine or split anything, it has to know which files exist in the app and how they depend on each other, and the graph is that knowledge. An **entry point** is a module the build is told to start from, typically the script the HTML page loads, or one entry per page in a multi-page app. Nothing reaches the graph except by a path of imports from some entry. ## How the walk proceeds The build runs a worklist algorithm: 1. Put every entry module on the worklist. 2. Take a module off the list and **load** it: read the file and run whatever transforms turn it into JavaScript the build can parse. 3. **Parse** it and collect every specifier it imports: `import … from`, `export … from`, side-effect `import './polyfills.js'`, and dynamic `import()` with a literal string. 4. **Resolve** each specifier to one absolute file path, using the importer's location and the package-manifest rules. 5. If that file is not yet a node, add it and put it on the worklist. Either way, record the edge. 6. Repeat until the worklist is empty. The walk is **static**: it reads specifiers from source text and never runs the app's code. The language requires a static `import` specifier to be a string literal, which is what lets a build tool know the whole static graph ahead of time. ## What counts as an edge | Import form | Followed by the walk? | What it means for the output | |---|---|---| | `import { a } from './a.js'` | Yes | `a.js` is loaded with the importer | | `import './setup.js'` | Yes | kept for its side effects even though nothing is bound | | `import('./charts.js')` with a literal | Yes | starts a branch that can load later | | `` import(`./locales/${lang}.js`) `` | Partly: some tools expand the fixed folder and extension into matching files | every match can be included | | `import(someVariable)` | No | left to the runtime, usually with a warning | | `require('./legacy.js')` in a CommonJS file | Yes | that file joins the graph, usually wrapped in a function | | a specifier marked **external** | Recorded, not followed | the import stays for the runtime to satisfy | | `import logo from './logo.svg'` | Yes | a non-JavaScript node handled as an asset | Which branches become separate chunks, and how stylesheets and images become output files, are separate subjects; here they are just nodes and edges. ## Identity: one node per resolved file A node is identified by the file it resolved to, not by the text of the specifier. `'./format'`, `'./format.js'` and `'../utils/format.js'` written in three different folders can all land on one node, so the file is included and evaluated once. The flip side matters in production: - Two specifiers that resolve to **different** paths for what you think is the same code create **two** nodes, and the code ships, and runs, twice. - Whether a symlinked folder counts by its link path or its real path changes which nodes exist. - Package entry rules (an `exports` map's conditions, the legacy entry fields) decide which file a package name lands on, and therefore which node. ## Why the graph matters in practice - **Unreachable code is excluded.** A file in `src/` that nothing imports is not in the output, however large the folder. - **Resolution errors surface at build time.** "Could not resolve './utils'" is the walk failing at step 4, before any browser is involved. - **Cycles are allowed.** If `a.js` imports `b.js` and `b.js` imports `a.js`, the second visit finds `a.js` already present and only records the edge; what a cycle does at run time is a language question, not a build one. - **Everything downstream reads the graph**: chunking, hot updates in development and source-map composition all start from it. ## Common misconceptions - "The bundler includes every file in the project folder." It includes what an import path reaches from an entry. - "A module imported by ten files is bundled ten times." It is one node with ten incoming edges. - "The build runs the code to find its imports." It parses; it never executes the app. - "Dynamic imports are invisible to the build." A literal `import()` is followed; only a fully computed specifier escapes the walk.
- What does marking a dependency as external do to the module graph?The build records the import but does not resolve, load or walk that specifier, so nothing behind it enters the output. The import is left for the runtime to satisfy: kept as an `import` or `require` in the output, or turned into a reference to a global the page defines. It suits libraries whose consumers supply the dependency and server bundles; in a browser app, an external that nothing provides fails when the page loads.
- Why does a specifier computed at run time, such as import(`./locales/${lang}.js`), weaken the graph?The walk reads specifiers from source text without running code, so a computed specifier cannot be resolved ahead of time. Some build tools expand a template with a fixed folder and extension into every matching file and include them all; a specifier with no static part is usually left for the runtime with a warning, and fails if the file it names was never emitted.
- The bundler includes every file in the source folder.
- A module imported by ten files ends up in the bundle ten times.
- An import cycle makes the module graph impossible to build.
- A dynamic import with a literal path is invisible to the build.
- The bundler runs the application code to discover its imports.