How Bundling Works
A bundler takes an entry file, follows every import to build a module graph, transforms each module (TypeScript, JSX, CSS…), and writes the graph out as a few files a browser or Node can load efficiently. esbuild, Rollup, Webpack, Parcel and Vite all do these steps; they differ in speed, output format and how much they let you plug into each step.
| Step | What happens |
|---|---|
| 1. Resolve | turn './math.js' or 'lodash' into a file path (the Node algorithm plus browser/module fields and aliases) |
| 2. Load + transform | read the file; strip types, compile JSX, inline JSON, run loaders/plugins |
| 3. Parse | find this module's imports and exports (an AST, not regexes) |
| 4. Link | connect each import to the export it refers to; detect cycles |
| 5. Tree shake | drop exports nobody imports (next lesson) |
| 6. Chunk | decide which modules go into which output file (code splitting) |
| 7. Generate | print the code, rename to avoid collisions, minify, write source maps |
A bundler in 50 lines
This model does steps 1, 3, 4 and 7 for a tiny CommonJS-flavoured bundler, the way early Webpack did: each module becomes a function in a table, and a small runtime implements require over that table.
// The "file system": three modules.
const files = {
'/src/index.js': `const { add } = require('./math.js');
const { greet } = require('./greet.js');
console.log(greet('bundle'), add(2, 3));`,
'/src/math.js': `exports.add = (a, b) => a + b;
exports.mul = (a, b) => a * b;`,
'/src/greet.js': `const { add } = require('./math.js');
exports.greet = (name) => 'hello ' + name + ' #' + add(1, 1);`,
};
const resolve = (from, spec) => from.slice(0, from.lastIndexOf('/')) + spec.slice(1); // './x' only
// Steps 1-4: walk the graph from the entry, giving every module an id.
function buildGraph(entry) {
const ids = new Map(), modules = [];
(function visit(path) {
if (ids.has(path)) return ids.get(path);
const id = modules.length;
ids.set(path, id);
const mod = { id, path, deps: {} };
modules.push(mod);
for (const [, spec] of files[path].matchAll(/require\('([^']+)'\)/g)) {
mod.deps[spec] = visit(resolve(path, spec));
}
return id;
})(entry);
return modules;
}
// Step 7: generate one file: a module table plus a tiny runtime.
function generate(modules) {
const table = modules.map((m) =>
` ${m.id}: [function (require, exports) {\n${files[m.path].replace(/^/gm, ' ')}\n }, ${JSON.stringify(m.deps)}],`).join('\n');
return `(function (modules) {
const cache = {};
function load(id) {
if (cache[id]) return cache[id].exports;
const module = (cache[id] = { exports: {} });
const [fn, deps] = modules[id];
fn((spec) => load(deps[spec]), module.exports);
return module.exports;
}
load(0);
})({
${table}
});`;
}
const graph = buildGraph('/src/index.js');
for (const m of graph) console.log(m.id, m.path, m.deps);
const bundle = generate(graph);
console.log('--- bundle:', bundle.split('\n').length, 'lines');
console.log(bundle.split('\n').slice(0, 9).join('\n'));
console.log('--- running the bundle:');
new Function(bundle)();0 /src/index.js { './math.js': 1, './greet.js': 2 }
1 /src/math.js {}
2 /src/greet.js { './math.js': 1 }
--- bundle: 25 lines
(function (modules) {
const cache = {};
function load(id) {
if (cache[id]) return cache[id].exports;
const module = (cache[id] = { exports: {} });
const [fn, deps] = modules[id];
fn((spec) => load(deps[spec]), module.exports);
return module.exports;
}
--- running the bundle:
hello bundle #2 5
Three observations that carry over to the real tools:
math.jsis in the graph once although two modules import it, and thecachemakes it execute once.- The bundle still contains
mul, which nobody uses. A function-table bundle can't easily remove it; that's what ES modules and tree shaking fix. - Every module pays for a wrapper function and a table lookup. Modern bundlers scope-hoist ES modules instead: they concatenate the modules into one scope, renaming variables where names collide, so there's no runtime at all. Rollup and esbuild do this by default; Webpack does it in production mode ("module concatenation").
The real graph: esbuild's metafile
esbuild can write out the graph it built, as JSON (--metafile), and summarise it (--analyze):
mkdir -p graph/src && cd graph
npm init -y > /dev/null && npm pkg set type=module
npm install ms@2.1.3 > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > src/math.js <<'JS'
export const add = (a, b) => a + b;
export const mul = (a, b) => a * b;
JS
cat > src/greet.js <<'JS'
import { add } from './math.js';
export const greet = (name) => `hello ${name} #${add(1, 1)}`;
JS
cat > src/index.js <<'JS'
import ms from 'ms';
import { add } from './math.js';
import { greet } from './greet.js';
console.log(greet("bundle"), add(2, 3), ms(90000));
JS
npx esbuild src/index.js --bundle --format=esm --outfile=dist/app.js --metafile=meta.json --analyze 2>&1 | grep -v Done
jq -r '.inputs | to_entries[] | "\(.key) <- imports: \([.value.imports[].path] | join(", "))"' meta.json
node dist/app.js
dist/app.js 4.5kb 100.0%
├ node_modules/ms/index.js 2.8kb 63.6%
├ src/index.js 112b 2.5%
├ src/greet.js 53b 1.2%
└ src/math.js 27b 0.6%
dist/app.js 4.5kb
node_modules/ms/index.js <- imports:
src/math.js <- imports:
src/greet.js <- imports: src/math.js
src/index.js <- imports: node_modules/ms/index.js, src/math.js, src/greet.js
hello bundle #2 5 2m
The analysis lists every input with its share of the output: ms (a CommonJS package) is most of this bundle. On a real app this view answers "why is my bundle 2 MB?" in seconds; the Toolkit lesson shows more tools for it.
Test yourself
In the model bundler, why does math.js run only once even though two modules require it?
- It is copied once into the bundle and its exports are cached by module id
- JavaScript runs files once automatically
- greet.js doesn't really import it
- The bundler deletes duplicates at runtime
What does scope hoisting (module concatenation) replace?
- Minification
- The per-module wrapper functions and runtime require, by putting modules in one scope
- Source maps
- Tree shaking
Which step decides which modules end up in which output file?
- Resolve
- Parse
- Chunking (code splitting)
- Minify