← JavaScript

Advanced · 11 of 11 · 11 min read

Build tooling

What a bundler actually produces, why transpiling and bundling are different jobs, and the terms you are expected to use correctly.

  • Tooling

Nobody ships the files they wrote. Between your src/ folder and the browser sit four separate jobs that get lumped together as “the build”, and an interview expects you to keep them apart.

The four jobs

Job Input → output Why
Bundling many modules → few files fewer requests, and the browser does not resolve imports
Transpiling new syntax → older syntax support engines that lack a feature
Minifying readable code → short code bytes over the wire
Tree shaking all the code → only what is reached drop what nothing imports
// What you write: three files
// utils.js  export const add = (a, b) => a + b; export const unused = () => {};
// math.js   import { add } from './utils.js'; export const double = (n) => add(n, n);
// main.js   import { double } from './math.js'; console.log(double(21));

// What ships, after bundling + tree shaking + minifying:
// console.log(42 /* or */ (n=>n+n)(21));

unused is gone because nothing imported it — that is tree shaking, and it works because import/export are static: the bundler can see the whole graph without running anything. require() is a function call with a computable argument, which is why CommonJS tree-shakes badly.

// Analysable at build time:
import { add } from './utils.js';

// Not analysable — the path is only known at runtime:
const name = Math.random() > 0.5 ? 'a' : 'b';
// const mod = require(`./${name}.js`);

Why bundle at all

Historically: one HTTP/1.1 request per module, and a hundred modules meant a hundred round trips. HTTP/2 multiplexes, so that argument is weaker — but bundling still wins on three counts:

  • Bare specifiers. import { z } from 'zod' is not a URL. A browser cannot resolve it without an import map; a bundler resolves it from node_modules.
  • Non-JS imports. import './styles.css' and importing an SVG are bundler inventions.
  • Whole-program optimisation. Tree shaking, minification and inlining need the whole graph.

Development is the opposite case, which is why modern dev servers do not bundle: they serve your modules natively and transform them one at a time, so a change rebuilds one file instead of the application.

Dev server (unbundled) Production build
Transform per file, on request the whole graph
Rebuild after an edit one module the affected chunks
Tree shaking no yes
Minified no yes
Source maps yes yes, usually separate

Code splitting

Having bundled everything into one file, you then split it again — because a user landing on the home page should not download the admin dashboard.

// Static: always in the initial bundle
import { formatDate } from './format.js';

// Dynamic: its own chunk, fetched only if this line runs
async function openEditor() {
  const { Editor } = await import('./editor.js'); // a separate request, on demand
  return new Editor();
}

A dynamic import() is the instruction to the bundler to cut the graph there. The usual seams are routes, modals, and anything heavy that most sessions never open — a chart library, a rich-text editor, a PDF viewer.

Transpiling and targets

// What you write
const greet = (name) => `Hi ${name}`;
const value = user?.profile?.name ?? 'anon';

// What a transpiler emits for an old target
var greet = function (name) { return 'Hi ' + name; };
var value = user != null && user.profile != null && user.profile.name != null
  ? user.profile.name
  : 'anon';

Two distinctions worth stating precisely:

  • Transpiling rewrites syntax — arrows, classes, optional chaining. It is a text transformation.
  • A polyfill supplies a missing runtime feature — Promise, Array.prototype.at, fetch. No amount of rewriting creates those; they have to be shipped as code.
// Syntax: transpilable
const [a, ...rest] = [1, 2, 3];

// Runtime: needs a polyfill on an engine that lacks it
console.log([1, 2, 3].at(-1)); // 3

The target matters more than people assume: every year of support you add costs bytes and performance, because the output is more verbose than the original.

Source maps

Minified code is unreadable, so the build emits a map from the shipped bytes back to your source. The browser reads it and shows you your own file in the debugger and in stack traces.

// at the end of the bundle
//# sourceMappingURL=main.js.map
// Without a map:
//   at t (main.min.js:1:48213)
// With one:
//   at createOrder (src/orders/create.js:42:11)

For production the usual arrangement is to generate maps and upload them to the error tracker rather than serve them publicly — you get readable traces without publishing your source.

The terms, used correctly

Term What it is
Bundler builds the module graph and emits chunks — webpack, Rollup, esbuild, Vite
Transpiler rewrites syntax — Babel, SWC, TypeScript’s emitter
Minifier shortens and mangles — Terser, esbuild
Entry point where the graph starts
Chunk one output file the bundler produced
Tree shaking dead-code elimination across the module graph
Code splitting deliberately producing more than one chunk
Hot module replacement swapping an updated module in without a reload
Side effect a module that does something on import, so it cannot be shaken out

That last one causes real bugs. A module whose import has an effect — a polyfill, a CSS import, a registration — must not be removed, which is what "sideEffects": false in a package.json promises:

import './analytics.js';  // imported for its effect; nothing is used from it

Marking a package side-effect-free when it is not means the bundler drops that import and the effect silently never happens.

What this project does

A concrete example, since the build you are reading this on is small:

  • Pages are rendered at build time, so no framework ships for a static page.
  • The quiz is one island, hydrated on its own; everything else is HTML.
  • Code highlighting runs at build time — the highlighter never reaches the browser, which is worth checking after a change, because it is easy to import a library into client code by accident.
# the check that matters here
grep -l shiki dist/_astro/*.js   # must find nothing

The general lesson: the cheapest kilobyte is the one you never send, and the way to know is to look at the output rather than at the dependency list.

Common mistakes

Calling transpiling and polyfilling the same thing

Mistake. “Babel makes Promise work in old browsers.” Why it fails. Babel rewrites syntax; Promise is a runtime object and has to be shipped as a polyfill. A transpiled file using Promise still fails on an engine that has none. What to do instead. Keep the two separate when you talk about them — syntax versus runtime.

Importing a whole library for one function

Mistake. import _ from 'lodash' to use debounce. Why it fails. The default import pulls the whole package, and a CommonJS build cannot be tree-shaken out of it. What to do instead. import debounce from 'lodash/debounce', a module-format package, or fifteen lines of your own.

Shipping without looking at the output

Mistake. Trusting that the bundle is small because the source is. Why it fails. One stray import of a date or icon library can double it, and nothing in the source makes that visible. What to do instead. Check the built sizes, and treat an unexplained jump as a bug to investigate rather than a number to accept.

Check yourself

One question from the bank on what you just read. Answering here does not affect your quiz history.

What is a bundle?

Practise Tooling →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.