# 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:

![Mermaid Diagram](https://mermaid.ink/img/pako:eNpFkVtrG0EMhf-KqqcWxhvSpi-mBJLipIUWG5uWwk4e5F2tV_Vclhn5luD_Xjx2k7fRcM6nI-kFm9gyjrFzcdf0lBR-zG0AAJjUFidB0wE6cfxlma5uc2quJLS8r_5mi08wGt3CvLZ4XcGcc3Tbi2zgRjrhBBqBIDG5wrD4dEbPi3NWW_xYwYxSPvs6CS2IH2LSDBRa4H15v_pmxfdYW_xUwf1GXAvaM6wSDX0hJB6YFLqYgLecDhfaK-CxAKa1xZsKpoOKl2eG93FQiYHchwLRxAy5pzUbyIMTBQkaoek3Yf2WZVpQf2qLnyuYeNFLgF0S5f9TGKC2hbQJKp5NUXgJ0h0M9JT7shUI5PnERYOekydpcfyC2rM_HabljjZO0Zx_flMSWjrOJ00Xgz6QF3fAMY5oGByP8iErewP3TsL6JzWLUj_EoAYsLngVGX59t2hgHpdRo4Fv7Las0pCBuyTkDGQKeZQ5SYemNFnI8ynL9c2wx-PR4HL1NbqYcIzvdr0o4_Ef8-TA_g?type=png)

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

```javascript
// 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:

![Mermaid Diagram](https://mermaid.ink/img/pako:eNpljjFPwzAQhf_KcRNITiUkpgxIQNXSIQsBlrjDNbkkLo4d2QdtqPLfURIGJMbvfXd674KlrxhTrK0_lS0Fgde1dgAAu0KjcRWfV8cI1-wkDDca95Ak97AtNDaBWVbHqHH_-zCrrNDYkbT_TV5ojELCf9V2UQtkC6DCjkNHpsL0gtJyNy2suKZPK6iW5J2CoYPlON3U3smGOmMHTDGhvrecxCEKdwoerXEfGZX5zBvvRIHGnBvP8LbTqODFH7x4Bc9sv1hMSQoegiGrIJKLSeRgalRzSW6-py23d_0Zx1HhoXny1gdM8erUGmEcfwCRy2qR?type=png)

Run natively (this project has `"type": "module"` in its `package.json`), it prints:

```text
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](https://github.com/acornjs/acorn), a small JavaScript parser (`npm i acorn`). Save this as `bundle.mjs`:

```javascript
// 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

```bash
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:

```javascript
"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:

![Mermaid Diagram](https://mermaid.ink/img/pako:eNqVkj9v2zAQxb_KlVMLUAUKdNIgoE1gx4MyWGgnL2fxLF1CkTJ58p8G_u4FpdqOES8dyffE93une1O1N6RyFWk7kKvpkbEJ2K0cAECPQbjmHp3AEjDCcnDCHX1UF0llZ-jw9SV-lOdJbgKR3JXLJHco7V21SmoUFBrlybDMimKRQxgcSEtATsIROm8G-49ukRXFPIdA24EDfV6pS7z6MjnmWVFU7x2XjLPj2QuB31GAKocZhyiQ6o-xUUMf2EmE64dAO7QDCpmV0hAoDlaAI9RYt2SmN6tsAqND74PEM8pU5-YyNSjf850ndMYr_6_AQ6KAliUH4ymC8zLODxtkp8cxRuwI_PqF6pE7kAzB3ZCX-dV4Q1veq3DNX-Tw7PeXFRknCCwR_N5B2kHYs7TTjmhAYwCdgbgdMJDSqqPQIRuVvylpqUsba2iDgxWlp5vfGBjXlmLybLyTGXZsjypXGfa9pSweo1Cn4adl91piXY3nmXeiYaUqajzBr0X6cUu_9uI1PJHdkXCNGn4ERqshootZpMAbpceQiv8klm_f-4M6nbRaNw_e-qBy9WnfspA6_QWs3B5N?type=png)

* * *

## 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:

```javascript
(() => {
  // 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:

![Mermaid Diagram](https://mermaid.ink/img/pako:eNp9kT9v3DAMxb8KyykHyBcE6OThgLj516Ed6jRL3YFn8SwlkuhK8l2c4L57oThAWgTIKP5IvveoZ-xFM9aY-M_EoecLS0Mk3wUAgJFitr0dKWRogBI0UQ6J43vaFtpy3Be44KbabNoari9vwQbNj9UvQ8n8Xt8nOMmGgUOOM_RmCg-rZaKtqs2mqf8lC_gumUH2HKGp4dYwjDQwxCmkdWHGhgF2UTw4epqLgKEEW-YAWg7BCWnWMHNevzlraijJITL1hhNYP0rMJx2uT1-XdLh6F6Sgtxz_uy7sQ9OvEisYo3ibinYSt-cEFDSUk3jRk1uCoULP0ZPVWD9jNuzLL2ne0eQyqqVyR9HS1nEqPTsJ-Yq8dTPWWNE4Oq7SnDJ7BY2z4eEb9e3L-0pCVtBhy4Mw_PzaoYIfspUsCm7Y7TnbnhScR0tOQaKQqsTR7lC9iLT2qXg5-zw-4vGocDt8EScRa_x0MDYzHv8CMI7Gng?type=png)

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

-   [MDN: JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). Module syntax, live bindings and import maps.
    
-   [MDN: import statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import). Exactly what each import form means, including why extensionless imports cost extra on the web.
    
-   [esbuild documentation](https://esbuild.github.io/) and its [architecture notes](https://github.com/evanw/esbuild/blob/main/docs/architecture.md), which explain scanning, linking, tree shaking and code splitting in a real bundler.
    
-   [webpack: Tree Shaking](https://webpack.js.org/guides/tree-shaking/). Static imports, the `sideEffects` flag, and the common ways tree shaking silently fails.
    
-   [Announcing Vite 8](https://vite.dev/blog/announcing-vite8) and [Announcing Rolldown 1.0](https://voidzero.dev/posts/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](https://zyvop.com/how-a-javascript-bundler-works-ipxkh?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
