Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Projects and Practice

Project: Build a Mini Bundler

Project: write a tiny JavaScript bundler in Node.js that reads a dependency graph, wraps modules in a runtime and shakes unused exports. A hands-on way to understand webpack.

The best way to stop webpack from feeling like magic is to build a toy version. In this project you will write a miniature bundler in about 80 lines of JavaScript: it follows import statements to build a dependency graph, wraps each module in a function, adds a small runtime that implements require, and finally removes unused exports (a baby version of tree shaking). Everything runs right here in the page's Node.js runner, because the "files" live in an in-memory object.

This is a teaching stand-in, not webpack. It uses regular expressions instead of a real parser, supports only named imports and one-line export const declarations, and ignores caching, loaders and source maps. Real bundlers parse code into a syntax tree. The goal is to see the shape of the algorithm.

The plan

flowchart LR
  A["Entry file"] --> B["Read and transform<br/>(imports to require)"]
  B --> C["Find dependencies"]
  C --> D["Resolve paths<br/>and repeat"]
  D --> E["Graph of modules"]
  E --> F["Wrap in runtime<br/>(one output file)"]

The same pipeline webpack follows: entry, parse, resolve, graph, emit.

Webpack's own pipeline matches this: it starts at the entry, parses each module to find its dependencies, resolves them (the resolve options), applies loaders, and then emits chunks (see code splitting). Our version has one chunk.

Step 1: build the dependency graph

First we need file contents and a way to turn a relative request such as ./text.js into an absolute id such as ./src/text.js. Then we walk breadth-first from the entry, reading each file once.

Node.js Step 1: find every module reachable from the entry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that text.js is imported by two files but appears once. The graph.has(id) check also makes circular imports terminate instead of looping forever.

Step 2: transform modules and write the runtime

Browsers cannot run our import statements inside a single concatenated file, so we rewrite them into calls to a require function, and rewrite export const x into an assignment on an exports object. Each module becomes a function that receives require and exports. The runtime keeps a cache so a module runs once, exactly like webpack's __webpack_require__.

Node.js Step 2: emit one bundle and run it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The printed output is the same structure as a development bundle from webpack: a registry of module functions and a few lines of runtime. Each module's map translates the request string inside that module ('./text.js') into a global module id, which is the job of webpack's resolve step at build time.

Step 3: shake unused exports

Now add the marking-and-deleting idea from tree shaking. We collect the names that every module imports from every other, then delete export const lines nobody asks for. This version only handles one-line exports and ignores whether a deleted function was used internally, which a real tool must check.

Node.js Step 3: remove exports nobody imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Ideas to extend it

Try these on your own machine, where you can run Node with real files:

  1. Read the files with fs.readFileSync and write dist/bundle.js.
  2. Support import x from (default) and export default.
  3. Add a loader step: a function (source, path) => source applied before parsing, for example turning .txt files into export const text = "...".
  4. Detect and report circular dependencies.
  5. Emit a second file for modules loaded through import() and add a load.e(chunkId) function to the runtime (compare dynamic imports).
  6. Add a content hash to the output file name (see long-term caching).

What the toy hides

  • Parsing. Real bundlers use parsers such as Acorn (webpack) or SWC (Rspack) to build an abstract syntax tree; regular expressions break on strings, comments and nested braces.
  • Module semantics. ES modules use live bindings (an exported let that changes is seen by importers); our copies are snapshots.
  • Resolution. Node's algorithm looks for package.json, index.js, extensions and the exports field.
  • Scale. Caching, incremental builds, parallel work and source maps are most of the engineering in a real bundler.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the graph builder skip modules it has already seen?

    A visited check makes each module appear once and ends traversal when files import each other.
  2. 2. What does the runtime's cache guarantee?

    The registry stores exports after the first execution, matching how webpack's require works.
  3. 3. Why is a regex-based transform not safe for production?

    Source code has a grammar; only a real parser handles all cases correctly.
  4. 4. Which webpack feature corresponds to our resolve() function?

    Resolution maps an import request to a concrete file, which is exactly what resolve() does in our toy.

Summary

  • A bundler builds a graph from the entry by parsing imports and resolving paths.
  • Modules are wrapped in functions and loaded through a small runtime with a cache.
  • Tree shaking is: collect used exports, delete the rest.
  • Real tools add parsers, loaders, chunking, caching and source maps on this same skeleton.

Next: Project: A Production-Ready Config