Web Development

How a JavaScript Bundler Works

A bundler follows your imports, builds a dependency graph, and packs the modules into files a browser can load. Build a working 60-line bundler, then see what real bundlers add on top.

·
10 min read
·
AI-assisted

AI tooling disclosure

Generative AI materially contributed to this article.

Human review confirmed by the author.

How a JavaScript Bundler Works

TL;DR

  • A bundler starts at an entry file, follows every import to 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:

  1. Import specifiers are not URLs. import x from './utils' and import React from 'react' work in Node and in bundlers, but a browser needs a full file path, and bare names like react need 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.

  2. Request waterfalls. A browser only learns about an import after it has downloaded the file containing it. A chain like index.js to greet.js to state.js costs 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.

  3. 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:

flowchart LR
    E["Entry file<br/>src/index.js"] --> R["1. Resolve<br/>specifier to a real file"]
    R --> P["2. Parse<br/>find imports and exports"]
    P --> G["3. Build the graph<br/>repeat for every import"]
    G --> O["4. Optimize (optional)<br/>tree shake, split into chunks"]
    O --> X["5. Emit<br/>rewrite imports, add runtime,<br/>minify, hash file names"]

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:

flowchart TD
    I["index.js (entry)"] --> G["greet.js"]
    I --> M["math.js"]
    I --> S["state.js"]
    G --> S
    M --> S

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_modules lookup, package.json exports, and aliases.

  • Parse, with a real parser. acorn gives us an AST, so we look at actual ImportDeclaration nodes. Do not use a regex here. Given a file with one real import plus an import inside a line comment, a string, and a block comment, the regex /import\s+.*?\s+from\s+['"](.+?)['"]/g reports four imports, three of them fake. The parser reports one.

  • Graph. addModule calls itself for every import, and modules is 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' becomes const { add } = require("math.js"). An export function add becomes a plain function plus exports.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 a cache: the first require of a module runs it and stores its exports, and every later require returns the stored object. That cache is why state.js runs 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:

sequenceDiagram
    participant R as Runtime
    participant I as index.js
    participant G as greet.js
    participant M as math.js
    participant S as state.js

    R->>I: run the entry module
    I->>G: require("greet.js")
    G->>S: require("state.js")
    Note over S: First time: runs, prints "state.js evaluated", result is cached
    S-->>G: exports
    G-->>I: exports
    I->>M: require("math.js")
    M->>S: require("state.js")
    Note over S: Cache hit: does not run again, the same object is returned
    S-->>M: the same exports
    M-->>I: exports
    Note over I: Now index.js runs its own code with greet, add and square

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. Given export let n = 0; export function inc() { n++; }, native modules print n = 1 after calling inc(), and the toy prints n = 0.

  • Missing syntax and formats: export * from, destructured exports, import(), CommonJS, node_modules lookup, 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:

sequenceDiagram
    participant B as Browser
    participant S as Server

    B->>S: GET index-[hash].js (the entry chunk)
    S-->>B: entry chunk
    Note over B: The page runs. Nothing from lazy.js has been downloaded yet.
    B->>B: code reaches import("./lazy.js")
    B->>S: GET lazy-[hash].js
    S-->>B: lazy chunk
    Note over B: The import() promise resolves and the module runs

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

  1. Dynamic imports defeat analysis. With require(name) or import(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.

  2. Marking sideEffects: false wrongly 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.

  3. 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.

  4. CommonJS is the weak link. Heavy use of require and module.exports costs you tree shaking and scope hoisting.

  5. 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

  1. A bundler starts at an entry file and follows imports to build a graph of modules.

  2. It parses code (never regexes) to find imports and exports, and resolves each specifier to a file.

  3. Each module becomes a function, and a tiny runtime with a cache runs each one once.

  4. Because import and export are static, bundlers can tree shake, hoist scope and split code.

  5. Production tools differ from the toy in optimization and coverage, not in the basic idea.


Further reading

If this post helped, send it to the teammate who still thinks a bundler is a black box.

Comments(0)

Join the discussion by logging into your account.

No comments yet. Be the first to comment!

Alysaa Lissy

Passionate developer sharing knowledge about modern web technologies and best practices.

Subscribe to Alysaa Lissy's Newsletter

Direct email dispatches when new stories are published. Zero algorithms.