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