{"schemaVersion":"1.0","type":"TechArticle","types":["Article","TechArticle"],"slug":"how-a-javascript-bundler-works-ipxkh","url":"https://zyvop.com/how-a-javascript-bundler-works-ipxkh","title":"How a JavaScript Bundler Works","subtitle":"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.","tldr":"A bundler is simpler than it looks: start at one file, follow every import, and pack what you find into something a browser can run. Build a working 60-line bundler, check it against native modules and esbuild, then see exactly what tree shaking, code splitting and minification add.","keywords":["modules","esbuild","JavaScript","bundler","vite","build-tools","Web Development"],"entities":["Alysaa Lissy","modules","esbuild","JavaScript","bundler","vite","build-tools","Web Development","ZyVOP"],"keyTakeaways":["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.","Tree shaking, code splitting, minification and hashing are optimizations on the same graph."],"headings":["1. What a bundler does, and when you can skip it","2. The pipeline","3. A project to bundle","4. Build the bundler","5. Run it","6. Where the toy falls short","7. What real bundlers add","Why tree shaking is possible","Code splitting","8. The landscape in 2026","9. Gotchas that follow from the model","10. The mental model on one screen","Further reading"],"outboundLinks":["https://github.com/acornjs/acorn","https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules","https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import","https://esbuild.github.io/","https://github.com/evanw/esbuild/blob/main/docs/architecture.md","https://webpack.js.org/guides/tree-shaking/","https://vite.dev/blog/announcing-vite8","https://voidzero.dev/posts/announcing-rolldown-1-0"],"contentText":"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 &lt;script type=\"module\"&gt;. Three things push real projects toward bundling anyway: 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. 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. 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&lt;br/&gt;src/index.js\"] --&gt; R[\"1. Resolve&lt;br/&gt;specifier to a real file\"] R --&gt; P[\"2. Parse&lt;br/&gt;find imports and exports\"] P --&gt; G[\"3. Build the graph&lt;br/&gt;repeat for every import\"] G --&gt; O[\"4. Optimize (optional)&lt;br/&gt;tree shake, split into chunks\"] O --&gt; X[\"5. Emit&lt;br/&gt;rewrite imports, add runtime,&lt;br/&gt;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) =&gt; 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)\"] --&gt; G[\"greet.js\"] I --&gt; M[\"math.js\"] I --&gt; S[\"state.js\"] G --&gt; S M --&gt; SRun 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: 2state.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 &gt; 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) =&gt; path.relative(root, file); // a module's id is its path relative to the entry folder const modules = {}; // id -&gt; 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) =&gt; s.type === 'ImportNamespaceSpecifier'); const picks = node.specifiers.filter((s) =&gt; s !== ns).map( (s) =&gt; { 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' &amp;&amp; node.declaration) { const d = node.declaration; const names = d.type === 'VariableDeclaration' ? d.declarations.map((v) =&gt; 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 &amp;&amp; /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) =&gt; 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]) =&gt; `${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 &gt; dist/bundle.js node dist/bundle.jsRunning 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-&gt;&gt;I: run the entry module I-&gt;&gt;G: require(\"greet.js\") G-&gt;&gt;S: require(\"state.js\") Note over S: First time: runs, prints \"state.js evaluated\", result is cached S--&gt;&gt;G: exports G--&gt;&gt;I: exports I-&gt;&gt;M: require(\"math.js\") M-&gt;&gt;S: require(\"state.js\") Note over S: Cache hit: does not run again, the same object is returned S--&gt;&gt;M: the same exports M--&gt;&gt;I: exports Note over I: Now index.js runs its own code with greet, add and square6. 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: (() =&gt; { // 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) =&gt; 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-&gt;&gt;S: GET index-[hash].js (the entry chunk) S--&gt;&gt;B: entry chunk Note over B: The page runs. Nothing from lazy.js has been downloaded yet. B-&gt;&gt;B: code reaches import(\"./lazy.js\") B-&gt;&gt;S: GET lazy-[hash].js S--&gt;&gt;B: lazy chunk Note over B: The import() promise resolves and the module runsUsers 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) 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. 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. 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 require and module.exports costs 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 import and export are 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 sideEffects flag, 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.","contentHash":"sha256:2a5cf4baad32eb6fa88fa5190da1ceba4987dea3f33d9d0bad2decd9b2bc9810","authorName":"Alysaa Lissy","authorUrl":"https://zyvop.com/author/alysaa","authorSameAs":[],"category":"Web Development","tags":["modules","esbuild","JavaScript","bundler","vite","build-tools"],"audience":"Software engineers and developers building applications with Web Development","tone":"Instructional, practical, code-first","readingTimeMinutes":11,"wordCount":2673,"faqs":null,"primaryTopic":"Web Development","publishedAt":"2026-11-15T04:45:14.415Z","updatedAt":"2026-11-15T04:45:14.415Z","canonicalUrl":"https://zyvop.com/how-a-javascript-bundler-works-ipxkh"}