TL;DR
A bundler starts at an entry file, follows every
importto build a dependency graph, then packs the modules into one or a few files.The output is mostly an object of module functions plus a ten-line runtime with a cache. That is the whole trick.
Tree shaking, code splitting, minification and hashing are optimizations on the same graph.
Below is a 60-line working bundler, checked against native modules and esbuild.
1. What a bundler does, and when you can skip it
You give a bundler one entry file. It follows every import, collects every file it reaches, and writes them into the file or files you ship.
Do you need one? A small app does not. Browsers run ES modules natively with <script type="module">. Three things push real projects toward bundling anyway:
Import specifiers are not URLs.
import x from './utils'andimport React from 'react'work in Node and in bundlers, but a browser needs a full file path, and bare names likereactneed an import map. MDN points out that omitting extensions is costly on the web, because the browser would have to try several URLs until one works. A bundler resolves all of this at build time.Request waterfalls. A browser only learns about an import after it has downloaded the file containing it. A chain like
index.jstogreet.jstostate.jscosts three sequential round trips, and a real app has hundreds of modules. Even Vite, which deliberately serves unbundled modules in development, added an experimental bundled dev mode in version 8.1 because large apps can flood the browser with module requests.Build-time work. Compiling TypeScript and JSX, deleting unused code, minifying, and naming files by content hash so they can be cached forever.
2. The pipeline
Every bundler, from a 60-line toy to webpack, runs the same five steps:
Our toy will do steps 1, 2, 3 and 5. Step 4 is what separates a toy from a production tool, and we will look at it after.
3. A project to bundle
Four small files. state.js is imported by three files, so it is the interesting one: it should run once and be shared.
// src/state.js
console.log('state.js evaluated');
export const counter = { n: 0 };
// src/greet.js
import { counter } from './state.js';
export default function greet(name) {
counter.n++;
return `Hello, ${name}!`;
}
// src/math.js
import { counter } from './state.js';
export function add(a, b) {
counter.n++;
return a + b;
}
export const square = (x) => x * x;
export function unused() { // nothing imports this
return 'dead code';
}
// src/index.js
import greet from './greet.js';
import { add, square } from './math.js';
import { counter } from './state.js';
console.log(greet('world'));
console.log('2 + 3 =', add(2, 3), '| 4 squared =', square(4));
console.log('shared counter:', counter.n);
As a graph, with each file appearing once:
Run natively (this project has "type": "module" in its package.json), it prints:
state.js evaluated
Hello, world!
2 + 3 = 5 | 4 squared = 16
shared counter: 2
state.js evaluated appears once, and the counter reaches 2 because greet.js and math.js share the same counter object. A correct bundler must preserve exactly that.
4. Build the bundler
It uses acorn, a small JavaScript parser (npm i acorn). Save this as bundle.mjs:
// bundle.mjs: a toy bundler. Usage: node bundle.mjs src/index.js > dist/bundle.js
import fs from 'node:fs';
import path from 'node:path';
import * as acorn from 'acorn';
const entry = path.resolve(process.argv[2]);
const root = path.dirname(entry);
const idOf = (file) => path.relative(root, file); // a module's id is its path relative to the entry folder
const modules = {}; // id -> rewritten source code
function addModule(file) {
if (idOf(file) in modules) return; // already in the graph: shared module or a cycle
modules[idOf(file)] = ''; // claim the slot BEFORE recursing, so cycles terminate
const code = fs.readFileSync(file, 'utf8');
const ast = acorn.parse(code, { sourceType: 'module', ecmaVersion: 'latest' });
const edits = [], head = [], tail = []; // text replacements, and export lines to add
for (const node of ast.body) {
if (node.type === 'ImportDeclaration') {
const dep = path.resolve(path.dirname(file), node.source.value); // resolve './math.js' to a real file
addModule(dep); // the graph walk: follow the import
const req = `require(${JSON.stringify(idOf(dep))})`;
const ns = node.specifiers.find((s) => s.type === 'ImportNamespaceSpecifier');
const picks = node.specifiers.filter((s) => s !== ns).map(
(s) => { const from = s.type === 'ImportDefaultSpecifier' ? 'default' : s.imported.name; return from === s.local.name ? from : `${from}: ${s.local.name}`; });
edits.push([node.start, node.end,
ns ? `const ${ns.local.name} = ${req};` : picks.length ? `const { ${picks.join(', ')} } = ${req};` : `${req};`]);
} else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
const d = node.declaration;
const names = d.type === 'VariableDeclaration' ? d.declarations.map((v) => v.id.name) : [d.id.name];
edits.push([node.start, d.start, '']); // drop the `export` keyword
for (const n of names) (d.type === 'FunctionDeclaration' ? head : tail).push(`exports.${n} = ${n};`);
} else if (node.type === 'ExportNamedDeclaration') { // export { a, b as c }
edits.push([node.start, node.end, '']);
for (const s of node.specifiers) tail.push(`exports.${s.exported.name} = ${s.local.name};`);
} else if (node.type === 'ExportDefaultDeclaration') {
const d = node.declaration;
if (d.id && /Function|Class/.test(d.type)) {
edits.push([node.start, d.start, '']);
(d.type === 'FunctionDeclaration' ? head : tail).push(`exports.default = ${d.id.name};`);
} else edits.push([node.start, d.start, 'exports.default = ']);
}
}
let out = code; // apply the edits from the bottom up so positions stay valid
for (const [start, end, text] of edits.sort((a, b) => b[0] - a[0])) out = out.slice(0, start) + text + out.slice(end);
modules[idOf(file)] = [...head, out, ...tail].join('\n'); // function exports go first because functions are hoisted
}
addModule(entry);
const wrapped = Object.entries(modules).map(([id, src]) =>
`${JSON.stringify(id)}: function (exports, require) {\n'use strict';\n${src}\n}`).join(',\n');
process.stdout.write(`(function (modules) {
const cache = {};
function require(id) {
if (cache[id]) return cache[id].exports; // each module runs once, then is cached
const module = (cache[id] = { exports: {} });
modules[id](module.exports, require);
return module.exports;
}
require(${JSON.stringify(idOf(entry))}); // start at the entry
})({
${wrapped}
});
`);
How it maps onto the pipeline:
Resolve.
path.resolve(path.dirname(file), node.source.value)turns'./math.js'into a real path. The toy only handles relative paths with explicit extensions, which makes it as strict as a browser. Real bundlers add extension guessing,node_moduleslookup,package.jsonexports, and aliases.Parse, with a real parser. acorn gives us an AST, so we look at actual
ImportDeclarationnodes. Do not use a regex here. Given a file with one real import plus animportinside a line comment, a string, and a block comment, the regex/import\s+.*?\s+from\s+['"](.+?)['"]/greports four imports, three of them fake. The parser reports one.Graph.
addModulecalls itself for every import, andmodulesis the graph (module id to rewritten source). It claims its slot before recursing, so a shared module is added once and a cycle terminates instead of looping forever.Rewrite. An
import { add } from './math.js'becomesconst { add } = require("math.js"). Anexport function addbecomes a plain function plusexports.add = add. Edits are applied from the bottom of the file upward so earlier positions stay valid. Function exports go to the top of the module, because functions are hoisted, and that is what makes cycles between functions work.Emit. Each module becomes a function
(exports, require). A ten-line runtime holds acache: the firstrequireof a module runs it and stores itsexports, and every laterrequirereturns the stored object. That cache is whystate.jsruns once.
5. Run it
npm i acorn
node bundle.mjs src/index.js > dist/bundle.js
node dist/bundle.js
Running the bundle prints exactly the same four lines as the native run above, and as esbuild's bundle of the same project. Here is what the toy emitted for greet.js, next to its source:
"greet.js": function (exports, require) {
'use strict';
exports.default = greet;
const { counter } = require("state.js");
function greet(name) {
counter.n++;
return `Hello, ${name}!`;
}
}
The import became a require, the export default became exports.default = greet (placed first, since the function is hoisted), and 'use strict' restores the strict mode that ES modules always have. Now the runtime in action:
6. Where the toy falls short
We tested it against native ES modules on more than the demo, and it matches on cycles between functions, namespace imports (import * as), export lists (export { a, b as c }), default classes and expressions, and side-effect imports. Here is what it gets wrong or cannot do:
Live bindings. ES module exports are live views, not copies. Our
const { n } = require(...)copies the value at import time. Givenexport let n = 0; export function inc() { n++; }, native modules printn = 1after callinginc(), and the toy printsn = 0.Missing syntax and formats:
export * from, destructured exports,import(), CommonJS,node_moduleslookup, and anything that is not plain JavaScript (TypeScript, JSX, CSS).No optimization at all. For these four tiny files, the toy's output is 1,374 bytes. esbuild's bundle of the same project is 460 bytes, and 256 bytes minified. The toy even ships
unused().
7. What real bundlers add
All of it hangs off the same graph:
| Feature | What it does | Seen in our demo |
|---|---|---|
| Tree shaking | Removes exports that nothing imports | esbuild's bundle has no unused(). Ours does. |
| Scope hoisting | Puts all modules in one scope instead of wrapping each in a function | esbuild's output (below) has no wrappers and no require |
| Minification | Shortens names and strips whitespace | 460 bytes down to 256 |
| Code splitting | Turns import() into a separate file fetched on demand | esbuild emitted index.js plus lazy-[hash].js |
| Content hashing | Puts a hash of the content in the file name | index-D6X7TGGX.js |
| Source maps | Maps output positions back to your source | --sourcemap |
| Loaders and plugins | Teach the bundler to treat CSS, TypeScript or images as modules |
Here is esbuild's bundle of the same four files, unminified:
(() => {
// src/state.js
console.log("state.js evaluated");
var counter = { n: 0 };
// src/greet.js
function greet(name) {
counter.n++;
return `Hello, ${name}!`;
}
// src/math.js
function add(a, b) {
counter.n++;
return a + b;
}
var square = (x) => x * x;
// src/index.js
console.log(greet("world"));
console.log("2 + 3 =", add(2, 3), "| 4 squared =", square(4));
console.log("shared counter:", counter.n);
})();
Notice three things. The modules appear in dependency order (state, greet, math, index), which is the order our runtime executes them. All import, export and require are gone, because one scope makes them unnecessary. And unused() has been removed.
Why tree shaking is possible
import and export are static: they must sit at the top level of a module, and their names are known before any code runs. A bundler can therefore see exactly which exports are used without executing anything. CommonJS module.exports is dynamic, which is why tree shaking works poorly with it, and the webpack documentation says it needs ES2015 module syntax. The same logic explains why a side-effect import such as import './polyfill.js' can never be dropped, and why packages declare "sideEffects": false in package.json to tell the bundler that unused imports from them are safe to remove.
Code splitting
Code splitting turns a dynamic import() into a boundary between files:
Users pay for the code they actually use. In esbuild, splitting is opt-in (--splitting) and only works with --format=esm (we checked with version 0.28: it rejects cjs).
8. The landscape in 2026
The tools differ in speed, defaults and plugin systems, not in the model. webpack is the long-standing, highly configurable option. Rollup is an ESM-focused bundler. esbuild is a fast bundler written in Go. Rolldown is a Rust bundler with a Rollup-compatible plugin API, stable (1.0) since May 2026. Vite 8, stable since March 2026, replaced its old esbuild-plus-Rollup combination with Rolldown, so development and production builds now use one bundler.
9. Gotchas that follow from the model
Dynamic imports defeat analysis. With
require(name)orimport(name), a fully computed name means the bundler cannot know which files you need, so it skips the call, warns, or includes more than necessary, depending on the tool.Marking
sideEffects: falsewrongly deletes code. If a file really does something on import and you tell the bundler it does not, it will be dropped, and the app breaks only in the production build.Duplicate packages are duplicate modules. The graph is keyed by resolved file path, as in our toy. Two versions of a library on disk are two modules, and both ship.
CommonJS is the weak link. Heavy use of
requireandmodule.exportscosts you tree shaking and scope hoisting.Small differences between bundlers show up at runtime. The classic example is how a CommonJS default import is interpreted, which is why it pays to test the production build, not only the dev server.
10. The mental model on one screen
A bundler starts at an entry file and follows imports to build a graph of modules.
It parses code (never regexes) to find imports and exports, and resolves each specifier to a file.
Each module becomes a function, and a tiny runtime with a cache runs each one once.
Because
importandexportare static, bundlers can tree shake, hoist scope and split code.Production tools differ from the toy in optimization and coverage, not in the basic idea.
Further reading
MDN: JavaScript modules. Module syntax, live bindings and import maps.
MDN: import statement. Exactly what each import form means, including why extensionless imports cost extra on the web.
esbuild documentation and its architecture notes, which explain scanning, linking, tree shaking and code splitting in a real bundler.
webpack: Tree Shaking. Static imports, the
sideEffectsflag, and the common ways tree shaking silently fails.Announcing Vite 8 and Announcing Rolldown 1.0. The current state of the tool most new projects use.
If this post helped, send it to the teammate who still thinks a bundler is a black box.
Published via ZyVOP — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.
Top comments (0)