Volume 2 Companion: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Companion: The Web Frontend

V2·30

Build Tooling and Monorepos

Companion to Volume 2, chapter 30: how packages, bundlers and monorepo tools connect; new angles (a lockfile as a bill of materials, hoisting as a shared pantry, a reproducible build as a recipe that gives the same cake in any kitchen); what the chapter simplifies, measured on the build's stage 30: a contract that changed shape over time and broke the kitchen display on one old order; two clean builds that were identical once the build's inputs were stated, and a deleted module that kept shipping; three copies of TypeScript in one workspace and a package imported without being declared; the theory behind reproducibility and content addressing; how npm's Arborist decides where a package goes; four debugging drills; interview questions with how to approach each.

6 sections · ~12 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 30 has five parts: packages and dependencies (npm and pnpm, lockfiles, workspaces), module systems (ESM, CommonJS, package exports), bundlers and compilers (what a bundler does, the tools, Vite, source maps), code quality (dependency auditing, ESLint, Prettier and Biome) and monorepos (task graphs, affected builds, caching, Turborepo, Nx, Bazel, releasing packages).

packages building at scale package managers npm, pnpm lockfiles exact tree, integrity workspaces hoisting, phantoms ESM and CommonJS package exports auditing install scripts, CVEs bundlers graph, tree shaking the tools esbuild, Rollup, Vite source maps back to the source lint and format ESLint, Biome reproducible output same inputs, same bytes monorepos one repo, many packages task graphs what depends on what affected builds only what changed caching hash the inputs releasing versions, changelogs writes shared by resolves and built by emit and then run by narrowed to skipped by then goes deeper: ch16 TypeScript · ch27 performance (bundle size) · ch28 supply chain · ch31 deployment · Volume 8 CI/CD exercises: P1–P9 ranges, phantoms, dual packages, bundles, source maps, secrets, Turborepo, lint, Changesets; C1–C3 monorepo, migration, secure pipeline
Concept map of chapter 30, build tooling: packages and dependencies (package managers, lockfiles, workspaces), module systems (ESM, CommonJS, package exports), bundlers and compilers (what a bundler does, the tools, Vite, source maps), code quality (auditing, ESLint, Prettier and Biome) and monorepos (task graphs, affected builds, caching, Turborepo, Nx, Bazel, releasing), with links such as the lockfile pinning what the bundler reads and a task graph's cache depending on declared inputs.

The links worth remembering:

  • Every stage is a function of its inputs, if you let it be. The lockfile fixes the dependencies, the bundler turns sources into output, the cache skips work whose inputs haven't changed. All three fail the same way: an input nobody declared (an environment variable, a stale file, a hoisted package).
  • What ships is mostly not yours. The bundle report in stage 30 found TiffinBox's own code was 9% of the React view. Dependency choices dominate size, risk and build time.
  • Monorepo tools are build graphs with memory. A task graph says what depends on what; caching says what can be skipped. Both are only as correct as the declared inputs.

Explain it differently

1. package.json is a shopping list; the lockfile is the receipt. The list says "milk, any brand under ₹60" (a version range). The receipt says exactly which carton, from which shop, with its barcode (version, URL, integrity hash). npm ci shops from the receipt; npm install may shop from the list and write a new receipt.

2. A lockfile is a bill of materials. Like the parts list of a car, it records every component down to the screws (transitive dependencies). When a part is recalled (a CVE, a compromised package), the bill of materials tells you in seconds whether you have it.

3. Hoisting is a shared pantry. In a workspace, each team's ingredients go into one shared pantry unless they need a different version, which they keep on their own shelf. Convenient, but anyone can take from the pantry what they never ordered (a phantom dependency), and it disappears when its real owner stops buying it.

4. A bundler is a removals company that packs only what's used. It walks the house from the front door (the entry point), packs everything reachable, leaves behind what nothing refers to (tree shaking), and labels boxes so you can find things later (source maps).

5. A reproducible build is a recipe that gives the same cake in any kitchen. If two kitchens following the recipe produce different cakes, either the recipe is incomplete (an undeclared input: the oven's temperature, the time of day) or someone tampered with one of them. Reproducibility lets you tell those apart.

6. A build cache is a cook who remembers. If the ingredients and the recipe are exactly the same as last time, serve last time's dish. If the cook forgets to check one ingredient (an environment variable), they serve yesterday's dish for today's order: the chapter's lab, Experiment 4.

7. Expand-then-contract is changing a road while traffic runs. Build the new lane, move traffic to it, then close the old one. Closing the old lane first strands every car still on it (every client still reading the old field).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from Node 22, npm 10.9.4 and the build's stage 30 (exp/30), unless stated.

1. A shared type is a promise across time, not just across files. The chapter treats shared types in a monorepo as the way client and server stay in step: change the type, and the compiler finds every use. That covers code built together. It doesn't cover data that was written before the change, or clients that were deployed before it. TiffinBox's contract (stage 16) called the pricing fields required; orders written before pricing was stored are sent without them, and one such order in the kitchen's snapshot made the whole display fail:

Terminal
ContractError: KitchenSnapshot.orders[0].discountPaise: expected a safe integer, got undefined

After stage 30 made those fields optional (explicitly, "discountPaise?"), the same snapshot parsed: parsed: [ 'o1', 'o2' ]. And the server can't simply rename a field now, because stage 29's service worker may serve yesterday's script to today's server: the old fields stay, marked deprecated, until stage 31 can tell old scripts from new. A type checked at compile time is one moment; a contract is all the moments at once.

2. Reproducible builds depend on stating the inputs, not just on the tools. The chapter explains why builds should be deterministic. Stage 30's two clean builds, in different directories, time zones, locales and umasks, gave identical output once the script knew what its inputs were:

Terminal
two clean builds: identical (22 files)
and identical to the committed build/web-manifest.json

The tools (TypeScript, esbuild, Angular's builder) needed no fixes. The two problems were inputs. The first version of the check left out web/ entirely and rebuilt 20 of 22 files, because two hand-written files live beside the outputs. And outputs that outlive their sources:

Terminal
web/kitchen/zz.js
differs: kitchen/zz.js
exit 1

A module compiled, then deleted from the source, stays in web/ (tsc never deletes) and keeps being served; only a clean build, or a manifest check, notices. "Same inputs, same output" is only useful if you know all the inputs, and the directory you build into is one of them.

3. A workspace is one install, not one version. The chapter presents workspaces as sharing dependencies. Stage 30's workspace has three copies of TypeScript:

Terminal
5.9.3 23M ./node_modules/typescript
6.0.3 24M ./node_modules/@schematics/angular/node_modules/typescript
6.0.3 24M ./web-src/angular/node_modules/typescript

Two copies of 6.0.3, because @schematics/angular was hoisted to the root (nothing there conflicted with it), but its own TypeScript requirement conflicted with the root's 5.9.3, so its copy nested under it; the Angular package's copy nested under the package. And the opposite surprise: hoisted packages are importable from anywhere in the repository:

Terminal
root package imported @angular/core 22.2.4
false

The root imported @angular/core without declaring it (false). pnpm's default layout prevents this (only declared packages are linked); with npm, stage 30's boundaries.mjs checks each bare import against its own package's package.json.

Common misconceptions

Misconception What's actually true Where it's shown
"Shared types keep client and server in step." Not with old data or old deployed clients; contracts need optional fields and expand-then-contract. Gaps 1
"Deterministic tools make reproducible builds." Undeclared inputs (stale files, hand-written files in the output) break it. Gaps 2
"A workspace has one version of each package." Three copies of TypeScript, two of them the same version. Gaps 3
"If it imports, it's a dependency." Hoisting makes undeclared packages importable. Gaps 3; drill D2
"npm install in CI is fine." It can change the lockfile; npm ci installs exactly it, or fails. Explain it differently 1
"Dependencies only run in the browser." Six packages ran native install scripts on every npm ci. Stage 30, step 4
"Our code is what makes the bundle big." It was 9% of the React view. Stage 30, step 4

Theoretical gaps: the ideas behind the chapter

1. Content addressing. Naming things by the hash of their content (Git objects, npm's integrity, hashed asset names, build caches) makes identity checkable: the same name means the same bytes, and a change of bytes changes the name. Stage 30's manifest and stage 31's hashed assets are both applications.

2. Reproducible builds and diverse double-compiling. If independent builders produce the same bytes from the same source, a compromised builder is detectable. The Reproducible Builds project and Debian rely on this; David A. Wheeler's diverse double-compiling extends it to detect a compromised compiler ("trusting trust").

3. Dependency resolution is constraint solving. Choosing versions that satisfy every range is NP-complete in general (it can encode SAT). npm avoids the hard case by allowing several versions at once (nesting); systems with one version per package (Cargo per major version, Go's minimal version selection, pip) solve or sidestep it differently. Go's MVS picks the minimum version that satisfies all requirements, making builds reproducible without a lockfile.

4. Build systems as incremental computation. Make, Bazel and Turborepo all compute "what must be rebuilt" from a dependency graph and a record of previous results. Build Systems à la Carte (Mokhov, Mitchell, Peyton Jones) classifies them by how they schedule (topological, restarting, suspending) and how they decide something is up to date (timestamps, hashes, traces).

5. Semantic versioning as a contract, and why it's weak. A version number is a promise about compatibility made by a person. Ranges trust that promise for every transitive dependency; lockfiles stop trusting it. Contract tests (stage 16's ContractTest) check the promise instead of trusting it.

Applying it

Code walkthrough

Gaps 3 found TypeScript in three places. The decision is made by npm's Arborist, in can-place-dep.js. Excerpts from @npmcli/arborist 8.0.1 as bundled with npm 10.9.4.

The algorithm, as its authors describe it

JavaScript
// The algorithm is roughly like this:
// - check the node itself:
//   - if there is no version present, and no conflicting edges from target,
//     OK, provided all peers can be placed at or above the target.
//   - if the current version matches, KEEP
//   - if there is an older version present, which can be replaced, then
//     - if satisfying and preferDedupe? KEEP
//     - else: REPLACE
//   - if there is a newer version present, and preferDedupe, REPLACE
//   - if the version present satisfies the edge, KEEP
//   - else: CONFLICT

Arborist tries a placement target (starting high, at the root's node_modules) and asks: can this package go here? OK and KEEP place it (or reuse what's there); REPLACE swaps the present version and re-resolves the displaced one; CONFLICT means try one level deeper. Hoisting is just "try the highest target first".

When something is already there

JavaScript
  checkCanPlaceCurrent () {
    const { preferDedupe, explicitRequest, current, target, edge, dep } = this

    if (dep.matches(current)) {
      if (current.satisfies(edge) || this.edgeOverride) {
        return explicitRequest ? REPLACE : KEEP
      }
    }

    const { version: curVer } = current
    const { version: newVer } = dep
    const tryReplace = curVer && newVer && semver.gte(newVer, curVer)
    if (tryReplace && dep.canReplace(current)) {
      const cpp = this.canPlacePeers(REPLACE)
      if (cpp !== CONFLICT) {
        return cpp
      }
    }

    // ok, can't replace the current with new one, but maybe current is ok?
    if (current.satisfies(edge) && (!explicitRequest || preferDedupe)) {
      return KEEP
    }

For @schematics/angular's TypeScript: the root already has 5.9.3 (current), the edge wants 6.0.3. 6.0.3 is newer, so Arborist tries to replace, but dep.canReplace(current) is false: the root package itself depends on exactly 5.9.3, and replacing would break that edge. The current one doesn't satisfy the edge either, so it isn't KEEP.

Deeper, or replace?

JavaScript
    const myDeepest = this.deepestNestingTarget

    // ok, i COULD be placed deeper, so leave the current one alone.
    if (target !== myDeepest) {
      return CONFLICT
    }

The root isn't the deepest place this TypeScript could live (it could nest under @schematics/angular), so it's a CONFLICT at the root, and Arborist tries the next target down: node_modules/@schematics/angular/node_modules/, where nothing conflicts. That's the second copy. The Angular package's own TypeScript follows the same path to web-src/angular/node_modules/. Nothing tries to share those two copies of 6.0.3, because no single location is visible to both and free of 5.9.3; the root is the only common ancestor, and it's taken.

Debugging drills

D1. The kitchen display is empty for one kitchen only

After restoring kitchen k3's data from an old backup, its display shows no orders and the console shows a ContractError about discountPaise. Every other kitchen is fine.

D2. The build breaks after an unrelated upgrade

The Angular team upgrades their package's dependencies. The next day the plain kitchen view fails to compile: Cannot find module '@angular/core' from a helper in kitchen/. Nobody on the plain view's team uses Angular.

D3. Production serves a module that was deleted

A security review finds web/kitchen/legacy-poll.js in production, although legacy-poll.ts was deleted months ago and nothing imports it.

D4. Two release candidates, different bytes

The release engineer builds the same commit twice to check, and the two react-kitchen.js files differ.

Career-oriented

Interview prep

Mid-level 1: lockfiles

Question. "What's the difference between npm install and npm ci, and which should CI run?"

How to get there. Say what each reads and writes, then what goes wrong with the wrong one.

Mid-level 2: why is the bundle so big?

Question. "Your React bundle is 600 KB. How do you find out why, and what do you do?"

How to get there. Measure first (by package, by module), then decide by what you find.

Senior 1: renaming a field in a public API

Question. "We need to rename pricedBy to something structured. Clients include our web app, two mobile apps and a partner. How?"

How to get there. Expand, migrate, contract, with how you know each phase is done.

Senior 2: is our build reproducible?

Question. "How would you make our frontend build reproducible, and why bother?"

How to get there. Why first (verification, incident response, supply chain), then how, then how to keep it.

Staff 1: monorepo or many repos?

Question. "Our 12 frontend repos share components by publishing packages, and upgrades take months. Someone proposes one monorepo. What's your view?"

How to get there. Name what each structure optimises, the costs that appear at scale, and how you'd decide.

Staff 2: supply-chain policy for builds

Question. "After a widely reported npm compromise, leadership asks what we do to protect our builds. What's the study plan?"

How to get there. Prevent, detect, respond, and what each costs developers.