1. What You Write vs. What Ships — Build Tools
“There are only two kinds of JavaScript: the kind you wrote, and the kind that runs.”— every source map, quietly
The story: the office where everyone was called $
Section titled “The story: the office where everyone was called $”Picture a small agency in 2009. The homepage has a jQuery carousel, a Prototype.js lightbox someone added in 2007, a MooTools menu from a plugin site, and a dozen <script> tags in the <head>, each one dumping its variables into one shared space called window.
One Monday, the carousel stops working. Nobody touched it. What changed? Someone added a new analytics script at the bottom of the page. That script defined a global function called $. So did jQuery. So did Prototype. Whichever loaded last won, and everyone else who called $('#hero') was now calling a stranger.
This is the office where everyone is named Raj. You shout “Raj, the invoice!” and five people look up, and the one who answers is the one who sat down most recently.
Everything in this chapter — modules, bundlers, tree-shaking, hashing — exists because of that office. We spent fifteen years building tools to give every piece of code its own name, its own room, and a precise list of who it talks to. And then we discovered that the browser couldn’t run any of those tools’ inputs directly, so we built more tools to translate. That’s the build step.
What the browser actually understands
Section titled “What the browser actually understands”Let’s be blunt about what a browser can execute. It speaks:
- HTML, CSS and JavaScript (the version it implements, which varies by browser and version).
- WebAssembly, images, fonts, audio and video in formats it supports.
That’s it. It does not understand:
- TypeScript. Types are not JavaScript.
let n: number = 1is a syntax error to a browser. - JSX.
<Button onClick={go} />inside a.jsfile is not JavaScript; it’s sugar forjsx(Button, { onClick: go }), and someone has to do that rewrite. - Bare imports.
import dayjs from 'dayjs'means nothing to a browser. A browserimportneeds a URL:./dayjs.jsorhttps://…/dayjs.js. The magic resolution “look innode_modules, read itspackage.json, find theexportsfield” is a Node.js convention, not a web one. - Sass, Less, CSS Modules, Tailwind directives, PostCSS plugins — all preprocessing conventions.
.svg?react,import styles from './x.module.css',import.meta.glob— bundler-specific dialects.
So the first job of a build tool is translation. The second, which turns out to matter more for users, is optimization: shipping the fewest bytes, in the fewest requests, in a form that caches well.
A short history of not being called $
Section titled “A short history of not being called $”The road from script-tag soup to today is worth knowing, because every tool you use still carries scars from it.
Globals (1995–~2009). Every script shares window. Order matters. Collisions are silent. Dependencies are implicit: if carousel.js needs jQuery, you’d better put jQuery’s tag above it, and nothing tells you if you didn’t.
The IIFE and the namespace (~2008). Developers wrapped code in an immediately invoked function expression — (function(){ … })() — so its variables lived in a private function scope, and exposed one global, like MyApp. This is the “module pattern.” Better, but dependencies were still implicit and ordering was still manual.
CommonJS (2009) and AMD (~2010). Node.js adopted CommonJS: const x = require('x') and module.exports = …. It’s synchronous — it reads files from disk mid-execution — which is fine on a server and impossible over a network. For browsers, AMD (RequireJS) offered an asynchronous define(['dep'], function(dep){ … }). It worked, and it was ugly enough that nobody was sad to see it go.
Bundlers (Browserify ~2011, webpack ~2012). The clever move: let developers write CommonJS, and at build time, walk all the require calls, find every file, and concatenate them into one big file with a tiny runtime that implements require. Now the browser downloads one file and dependencies are explicit.
ES Modules (standardized 2015, in browsers ~2017–2018). JavaScript finally got a native module system: import and export. Crucially, ESM is static: imports must be at the top level with literal strings, so a tool can know the entire dependency graph without running the code. That one property makes tree-shaking possible.
Transpiling: translating one JavaScript into another
Section titled “Transpiling: translating one JavaScript into another”A transpiler reads source code, turns it into a tree (an abstract syntax tree, or AST), transforms the tree, and prints code back out. “Source-to-source compiler” is the precise term.
The transformations come in three flavours:
- Strip what browsers don’t understand: TypeScript type annotations, interfaces,
ascasts. - Rewrite sugar: JSX into function calls, decorators into helper calls.
- Down-level new syntax for old browsers:
a?.bintoa == null ? void 0 : a.bif your target browsers don’t support optional chaining.
Babel (2014, originally “6to5”) was the workhorse for a decade: written in JavaScript, endlessly pluggable, and slow at scale. The current generation is written in systems languages and is 10–100× faster: esbuild (Go) and SWC (Rust, used inside Next.js), plus Oxc (Rust) inside the newest Vite toolchain.
TypeScript’s own compiler, tsc, can also emit JavaScript, but in most modern setups it does just one job: type-checking. The fast tools strip types without checking them — they don’t understand your types at all, they just delete them. That’s why your Vite dev server happily runs code with type errors, and why your CI must run tsc --noEmit separately (Chapter 3).
Bundling: one graph, few files
Section titled “Bundling: one graph, few files”A bundler starts from one or more entry points (say src/main.tsx), parses each file, finds its imports, resolves each import to a file on disk, and recurses. The result is a module graph. Then it decides how to cut that graph into output files (chunks) and writes them.
Why not just ship the modules as separate files, now that browsers support ESM? Three reasons, in order of how much they matter:
- Waterfalls. The browser only discovers
b.jsafter downloading and parsinga.js, which imports it. A deep graph becomes a chain of round trips. On Priya’s 80 ms RTT connection, a graph 10 levels deep costs most of a second in pure latency. HTTP/2 multiplexing doesn’t fix this, because the discovery is sequential. - Per-file overhead. Thousands of tiny files compress worse (compression works better on bigger inputs) and carry per-request costs.
- Optimizations need the whole graph. Tree-shaking, scope hoisting and smart chunking only work when the tool can see everything.
The bundler zoo, explained by what problem each solved
Section titled “The bundler zoo, explained by what problem each solved”- webpack (2012): the everything-tool. Loaders for any file type, a plugin for any need, configurable to the point of a career. Still everywhere, still slow-ish on big apps.
- Rollup (2015): built for ES Modules from day one; produced the cleanest output and popularized tree-shaking. The library author’s favourite.
- Parcel (2017): zero config. “Point me at an HTML file.” Fast, friendly.
- esbuild (2020): written in Go, roughly 10–100× faster than the JS tools. Proved that tool speed was a language problem.
- Vite (2020): not a bundler so much as a dev experience. Unbundled native ESM in development, a real bundler for production. More on this below.
- Turbopack (Vercel, Rust): webpack’s spiritual successor, incremental by design, and the default bundler in recent Next.js versions.
- Rolldown (Rust): a Rollup-compatible bundler built to give Vite one fast engine for both dev and production, replacing the esbuild-plus-Rollup split.
The trend is unmistakable: tools written in Rust or Go, sharing an AST across parsing, transforming, bundling and minifying so the code is parsed once instead of five times.
Minification
Section titled “Minification”A minifier makes code smaller without changing what it does: removing whitespace and comments, renaming local variables to single letters, folding constants (60 * 60 → 3600), removing dead branches (if (false) …), shortening syntax. Terser, esbuild and SWC all minify. Minified-then-compressed JavaScript is commonly a fifth to a tenth the size of the original source.
Minification matters less than you think for download time (Brotli would have squeezed the whitespace anyway) and more than you think for parse time: the browser still parses every byte it receives after decompression. Chapter 11 explains why a byte of JavaScript is the most expensive byte you can send.
Tree-shaking: deleting code nobody calls
Section titled “Tree-shaking: deleting code nobody calls”Tree-shaking is dead-code elimination at the module level. Because ESM imports are static, the bundler can see that you imported only format from a date library and drop the forty other exports. The name comes from shaking a tree so the dead leaves fall off.
But there’s a catch that bites every team eventually: side effects. Consider:
window.__track = []; // side effect: runs when the module is importedexport function track(e) { window.__track.push(e); }If you import { somethingElse } from './analytics.js', the bundler cannot safely delete the module even if you never call track, because merely evaluating the module changes the world. So it keeps it. Multiply by every module that touches window, registers a polyfill, or imports CSS, and tree-shaking quietly stops working.
That’s why package.json has a "sideEffects" field. "sideEffects": false is the library author promising: “importing any file in this package without using it does nothing; feel free to drop it.” "sideEffects": ["*.css"] says “except CSS files.”
Code-splitting and dynamic import()
Section titled “Code-splitting and dynamic import()”Bundling everything into one file is great until the file is 900 KB and the reader only wanted to see the homepage. Code-splitting cuts the graph into chunks that load on demand. The lever is dynamic import:
button.addEventListener('click', async () => { const { openEditor } = await import('./editor.js'); // fetched only now openEditor();});The bundler sees import('./editor.js') and makes editor.js and everything only it needs into a separate chunk. Frameworks do this per route automatically: in Next.js, every page is its own chunk.
The trade-off is the waterfall again. Split too finely and a route change triggers a cascade of small requests, each discovered only after the previous one executes. Chapter 10 will show you that cascade in a Performance trace, sitting right in the middle of a janky navigation. The best-practice answer: split by route and by heavy, rarely-used feature (editors, charts, maps), and prefetch the likely next route on hover or when the link becomes visible.
Source maps: a dictionary back to your code
Section titled “Source maps: a dictionary back to your code”Minified code is unreadable: function a(b){return b.c?d(b):e}. When it throws in production, the stack trace points at line 1, column 48,213. A source map is a JSON file that maps positions in the output back to positions in the original files, so DevTools and error trackers can show you Essay.tsx:42.
A bundle ends with a comment like //# sourceMappingURL=index-B7f3a9.js.map. DevTools fetches that file only when DevTools is open. Users never download it.
But anyone can download it, and many source maps embed your full original source (sourcesContent). Ship public source maps and you’ve published your source code, comments and all. That has happened to large companies more than once — whole proprietary codebases reconstructed from a .map file left on a public CDN or inside a published npm package. The fix is boring: generate maps, upload them privately to your error tracker (Chapter 23), and don’t deploy them publicly (or use “hidden” source maps that omit the comment and keep the files off the public server).
Hashing: names that change when content changes
Section titled “Hashing: names that change when content changes”Look at index-B7f3a9.js. That B7f3a9 is a hash of the file’s contents. Change one character and the hash — and therefore the file name — changes.
Why bother? Caching (Chapter 6). If a file’s name changes whenever its content changes, then a given URL always means the same bytes, forever. So you can tell every browser and CDN on earth: cache this for a year, never ask me again (Cache-Control: public, max-age=31536000, immutable). When you deploy, the HTML references the new names, browsers fetch the new files, and old ones simply stop being requested. Cache invalidation, one of the two hard problems in computer science, solved by renaming things — which is, fittingly, the other hard problem.
The HTML itself can’t be hashed (its URL is the address users type), so HTML gets a short cache or revalidation. Hashed assets + revalidated HTML is the winning strategy, and you’ll see it in every chapter of Part I.
CSS has a build step too
Section titled “CSS has a build step too”CSS goes through its own pipeline:
- PostCSS parses CSS into an AST and runs plugins (autoprefixer adds
-webkit-where your targets need it). - Tailwind scans your source files for class names and generates only the CSS for classes you actually used.
- Lightning CSS (Rust) parses, transforms, prefixes and minifies in one fast pass; recent Tailwind and Vite use it.
- CSS Modules rename
.titleto.Essay_title__x9f2so class names stop colliding — the CSS version of escaping the office full of Rajes.
The output is usually one hashed CSS file per entry or route. CSS is render-blocking (Chapter 9), so the size of that file directly delays first paint.
Targets, polyfills and browserslist
Section titled “Targets, polyfills and browserslist”Your code says structuredClone(x) and a ??= b. Priya’s phone runs a Chrome that’s two years old, and her cousin’s runs a WebView from 2021. Which features can you use?
Two separate problems hide here:
- Syntax (
??=, optional chaining, class fields) can be transpiled down. The transpiler rewrites it. - APIs (
structuredClone,Array.prototype.at,fetch) cannot be transpiled; they must be polyfilled — implemented in JavaScript and shipped to browsers that lack them.
You tell your tools what to target with a browserslist query ("> 0.5%, last 2 versions, not dead") or, increasingly, a Baseline target — “features that have been available in all major browsers for at least 30 months.” Get this wrong in one direction and you ship 40 KB of polyfills to people who don’t need them. Get it wrong in the other and your production build crashes on older devices with SyntaxError: Unexpected token '?' — an error that never appears on your own up-to-date laptop, which is the classic “works on my machine” build incident.
Dev server vs. production build
Section titled “Dev server vs. production build”Here’s a puzzle that confuses many experienced developers: Vite’s dev server is famously instant, but vite build takes a while. Why are they different?
In development, you want instant start and instant updates. Vite serves your source files as native ES Modules, transforming each file on request (stripping TS, compiling JSX) and never bundling your own code. Your browser does the module graph walk. For a big app that’s hundreds of requests — fine on localhost, where a round trip is ~0 ms. When you save a file, Hot Module Replacement (HMR) sends just that module to the browser over a WebSocket and swaps it in, often preserving component state.
In production, round trips are not free (Priya’s are 80 ms), so Vite bundles: tree-shakes, splits, minifies, hashes. Historically that meant two engines (esbuild for dev pre-bundling, Rollup for production), which could subtly disagree; the move to a single Rust engine (Rolldown) is about making dev and prod behave identically, faster.
The world with no build step
Section titled “The world with no build step”Is the build step mandatory? No, and knowing when to skip it is a senior skill.
Modern browsers support ES Modules natively, and import maps solve the bare-specifier problem:
<script type="importmap"> { "imports": { "dayjs": "/vendor/dayjs.esm.js" } }</script><script type="module"> import dayjs from 'dayjs'; // now resolvable: the map says where document.querySelector('time').textContent = dayjs().format('D MMM');</script>No Node, no node_modules, no config. Your CSS can use native nesting and custom properties; your JS can use everything Baseline supports.
When “no build” is a valid choice: small sites, prototypes, internal tools, documentation, a design-system playground, a UI kit made of vanilla HTML/CSS/JS (like the author’s glass kit in Chapter 16, which ships with zero dependencies — and loads in under 100 ms partly because of it). When it isn’t: you want TypeScript or JSX, you have a deep module graph (the waterfall), you have many npm dependencies, or you need hashing for long-term caching. The honest middle ground: a build step that does almost nothing, like Vite with default settings.
Reading next build like a senior engineer
Section titled “Reading next build like a senior engineer”Run next build on a Next.js app and you get a route table. A representative shape:
Route (app) Size First Load JS┌ ○ / 5.2 kB 112 kB├ ○ /about 1 kB 108 kB├ ● /essays/[slug] 3.4 kB 110 kB├ ├ /essays/monsoon├ └ /essays/chai├ ƒ /search 2.8 kB 110 kB└ ○ /dashboard 48 kB 155 kB+ First Load JS shared by all 107 kB
○ (Static) prerendered as static content● (SSG) prerendered as static HTML (uses generateStaticParams)ƒ (Dynamic) server-rendered on demandRead it like this:
- The symbol tells you where HTML is made (Chapter 7).
○and●are built once and served from a CDN — cheap and fast.ƒruns on your server for every request — flexible, costs TTFB and server CPU. A route you expected to be static showingƒusually means something made it dynamic (reading cookies or headers, an uncached fetch). That’s a real bug to chase. - Size is JavaScript specific to that route.
- First Load JS is what a visitor who lands directly on that route downloads: shared chunks + route chunk. The shared 107 kB is React, the framework runtime and your shared components. This is the number to budget (Chapter 18).
/dashboardat 155 kB says “something heavy lives here” — a charting library, probably. Fine for a logged-in dashboard; alarming for a landing page.
Exact output varies between Next.js versions (recent versions with Turbopack format it differently and may omit size columns), but the concepts — where HTML is made, and how much JS each entry costs — are the two questions to ask of any framework’s build output.
When builds go wrong
Section titled “When builds go wrong”- Leaked source maps publish your source (above).
- Mismatched targets ship syntax old devices can’t parse (above).
- Accidental bundling of server code — a secret-reading module imported into a client component — puts server logic, or worse, secrets, in a public bundle. Frameworks now fence this (
server-only,NEXT_PUBLIC_prefixes; Chapter 4). - Broken tree-shaking quietly bloats bundles by hundreds of KB after an innocent refactor adds a side-effectful import. Only a size check in CI catches this.
- Dev/prod divergence: works in
vite dev, fails aftervite build, because production does something dev doesn’t (minification renaming, chunking order, CSS ordering). Always test the production build locally before shipping.
What you now know
Section titled “What you now know”You can explain why a browser can’t run your source, what every stage of a build does, why tree-shaking silently fails, why dev servers are unbundled and production builds aren’t, when no build is the right call, and how to read a framework’s build output for the two numbers that matter. That’s more than most people who run npm run build every day.
Self-quiz
Section titled “Self-quiz”1. Why can’t a browser run import dayjs from ‘dayjs’ without help?
Browser imports need a URL. “Look in node_modules” is a Node convention. You need a bundler (which resolves it at build time) or an import map (which tells the browser where dayjs lives).
2. Your Vite app runs fine in dev despite a type error. Why?
Vite strips types with a fast transpiler; it doesn’t check them. Type-checking is a separate tsc --noEmit step.
3. What property of ES Modules makes tree-shaking possible?
Imports and exports are static (top level, literal strings), so the graph is knowable without executing code.
4. What does “sideEffects”: false promise?
That importing a file from the package without using its exports has no effect, so unused files can be dropped entirely.
5. Why does a content hash in a file name enable caching “forever”?
Because a URL then always refers to the same bytes. New content gets a new name, so there’s never a stale version to invalidate.
6. What’s the difference between transpiling and polyfilling?
Transpiling rewrites syntax into older syntax. Polyfilling adds missing APIs by shipping a JS implementation. You can’t transpile your way to structuredClone.
Exercises
Section titled “Exercises”Warm-up 1. Predict the waterfall. An unbundled app’s entry imports 3 modules, each of which imports 2 more, each of which imports 1 more. On an 80 ms RTT connection with no caching, roughly how much time is spent in round-trip latency just discovering modules?
Solution
Discovery is by depth, not count: 4 levels (entry, 3, 6, 6) → ~4 sequential round trips ≈ 320 ms, plus connection setup. Bundling collapses it to one.
Warm-up 2. Spot the side effect. Which of these modules can be tree-shaken if unused? (a) export const PI = 3.14; (b) import './styles.css'; export const x = 1; (c) Array.prototype.last = function(){…}.
Solution
Only (a). (b) imports CSS (a side effect), (c) mutates a global prototype.
Warm-up 3. Read the table. In the next build example above, a teammate’s PR changes / from ○ to ƒ. What probably happened, and why does it matter?
Solution
Something made the page dynamic — reading cookies/headers, or an uncached fetch. The homepage now renders per request on the server instead of being served from the CDN: higher TTFB, more server load, worse resilience.
Lab 4. Lumen, no tooling. Create lumen/index.html with a grid of six images, a style.css and an app.js that opens a lightbox on click. Use a <script type="module">. Open it via a local static server (modules don’t load from file://).
Hint and expected outcome
Any static server works (npx serve, python3 -m http.server). The DevTools Network panel should show exactly three requests plus images. Note this baseline; you’ll compare against it later.
Lab 5. Add a dependency without a build. Add a small date library to Lumen via an import map pointing at a vendored ESM file. Format each essay’s date.
Solution sketch
Download the library’s ESM build into /vendor, add <script type="importmap"> mapping the bare name, and import it from app.js. Watch the Network panel: the map adds no request; the library file is one more.
Lab 6. Introduce Vite. Move Lumen into a Vite project. Compare the Network panel in dev vs. preview (after build). Count requests and total bytes.
Expected outcome
Dev: many requests (one per module, plus Vite’s client). Preview: a handful of hashed files, smaller total. That difference is the whole argument of Figure 1.6.
Lab 7. Break tree-shaking on purpose. Import one function from a large utility library using a namespace import or a CommonJS build, build, and inspect bundle size with a visualizer plugin. Then switch to the ESM build with a named import.
What you should see
The CommonJS/namespace version pulls in most of the library; the ESM named import keeps a few KB. CommonJS’s dynamic require defeats static analysis.
Lab 8. Source maps, privately. Configure your build to produce source maps but not reference them from the bundle. Verify in DevTools that the deployed bundle has no sourceMappingURL comment.
Hint
Most bundlers support a “hidden” source map mode. You’ll upload these to an error tracker in Chapter 23.
Staff 9. Build or no build? A designer on your team wants to ship a vanilla HTML/CSS/JS component kit with zero tooling. Write a half-page recommendation: when is that the right call, what risks does it carry, and what minimal tooling (if any) would you add?
Model answer
Right call if the kit is small, dependency-free, targets modern browsers and values copy-paste portability. Risks: no hashing (so cache headers must be conservative or versioned by path), no type safety, manual dependency ordering if it grows. Minimal addition: a single build script that minifies and hashes for production while keeping source copy-pasteable, plus a lint step.
Staff 10. Explain it to a PM. Your PM asks why the team is “spending a sprint on build tooling.” In five sentences, connect bundle size and chunking to a user-visible outcome and to a business metric.
Model answer
“Our homepage ships 400 KB of JavaScript, and on a typical mid-range Android phone parsing and running that takes over a second before the page responds to taps. Most of it is code for pages the visitor never opens. Splitting by route and removing an unused library cuts the homepage to ~150 KB. We expect taps to respond noticeably faster on mobile, which is where most of our traffic and most of our drop-off is. We’ll measure it with field data before and after, so we’ll know if it paid off.”