FE·30
Build Tooling & Monorepos
How frontend code becomes deployable assets: package managers and lockfiles, workspaces, ESM versus CommonJS and package exports, bundlers (Vite, Rollup/Rolldown, esbuild, SWC, Rspack, Webpack, Turbopack), source maps, auditing, linting and formatting, and monorepo task graphs, affected builds and caching with Turborepo, Nx and Bazel.
Start here: from source files to a deployable site
Why there's a build step at all
The browser can run plain HTML, CSS and JavaScript files directly, and small sites need nothing more. Real apps add a build step because:
- You write code the browser can't run as-is: TypeScript and JSX must become JavaScript (chapters 16 and 22).
- You use hundreds of packages from npm, written as modules in different formats, which must be found and combined.
- Users should download as little as possible: minify code, remove unused code ("tree shaking"), split it into chunks loaded when needed (chapter 27).
- Files need content hashes in their names (
index-Cs1vsncV.js) so they can be cached for a year and still update instantly on deploy (chapter 19).
A bundler (Vite, esbuild, Rollup/Rolldown, Webpack, Rspack, Turbopack) does all of that: it starts at your entry file, follows every import, transforms each file, and writes a small number of optimised output files.
npm and package.json
npm is Node's package manager (pnpm, Yarn and Bun are popular alternatives that do the same job). A project's package.json lists what it needs and the commands it runs:
{
"name": "tiffin",
"private": true,
"type": "module",
"scripts": { "dev": "vite", "build": "vite build", "test": "vitest run" },
"dependencies": { "react": "^19.3.1", "react-dom": "^19.3.1" },
"devDependencies": { "vite": "^8.3.5", "vitest": "^5.0.5" }
}
npm installdownloads everything intonode_modules(including the dependencies of your dependencies, often hundreds of packages).npm run buildruns thebuildscript;npx viteruns a tool fromnode_moduleswithout a global install.dependenciesare needed by the app at run time;devDependenciesonly to build and test it.
Version ranges and the lockfile
Package versions follow semantic versioning: MAJOR.MINOR.PATCH, where a major bump may break you, a minor adds features compatibly, and a patch fixes bugs. package.json usually says a range, not a version. What each range would install for lodash today:
4.17.15 → newest matching: 4.17.15 exactly this version
~4.17.15 → newest matching: 4.17.23 patches only
^4.17.15 → newest matching: 4.18.1 minors and patches (npm's default when you install)
>=4.17.0 <4.18.0 → newest matching: 4.17.23
latest published: 4.18.1
So two developers running npm install a month apart could get different code. The lockfile (package-lock.json, pnpm-lock.yaml) records the exact version, download URL and integrity hash of every package actually installed; commit it, and use npm ci on build servers to install exactly what it says (and fail if it doesn't match package.json).
What a bundle looks like
Building chapter 26's shopping list with Vite:
$ npx vite build
✓ 15 modules transformed.
dist/index.html 0.29 kB │ gzip: 0.22 kB
dist/assets/index-Cs1vsncV.js 220.29 kB │ gzip: 68.97 kB │ map: 1,046.67 kB
✓ built in 596ms
Fifteen modules (your two files plus React's) became one minified JavaScript file with a hashed name, 69 KB once compressed, plus a source map (.map) that lets DevTools show your original code when debugging. dist/ is what you deploy (chapter 31). In development, npx vite instead started a dev server in 202 ms that serves your source files directly and updates the page instantly when you save (hot module replacement).
Tree shaking: only ship what you use
Bundlers can drop exports you never import, if the library is written as ES modules. Using one function (debounce) from lodash, two ways:
import _ from "lodash"; // the CommonJS build: one big object
export const search = _.debounce(q => console.log(q), 200);
import { debounce } from "lodash-es"; // the ES-module build: named exports
export const search = debounce(q => console.log(q), 200);
import _ from "lodash" 73,844 bytes minified, 26,444 gzipped
import { debounce } from "lodash-es" 2,928 bytes minified, 1,463 gzipped
The same feature cost 25× more with the first import. Prefer ES-module packages and named imports; check what a dependency adds before installing it (bundlephobia.com, or your bundler's analyser).
Source maps: debugging minified code
Minified code is unreadable: an error in it points at line 1, column 34 of a one-line file. A source map links each position back to your original file and line. The same thrown error in a minified Node build:
without source maps: at e (/tmp/V2/c30/sm/out.js:1:34)
with source maps: at priceWithGst (/tmp/V2/c30/sm/price.js:2:29)
Browsers apply source maps automatically in DevTools; error-tracking services (chapter 32) apply them to production stack traces if you upload the maps.
Linting and formatting
Two more tools run on every save and every commit:
- A formatter (Prettier, or Biome) rewrites code into one consistent layout, so reviews discuss logic rather than spacing.
- A linter (ESLint, Biome, oxlint) finds likely bugs and risky patterns: unused variables, missing
await, React hook rule violations, accessibility problems in JSX, imports that break your architecture rules (chapter 21).
Monorepos, briefly
Larger organisations often keep many apps and shared packages (a design system, an API client) in one repository, a monorepo, using the package manager's workspaces to link them. Tools like Turborepo and Nx then run tasks in dependency order and cache results, so unchanged packages aren't rebuilt. In the lab, a second build with nothing changed took 5 ms instead of 5 seconds.
How deep to go in build tooling
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain package managers, semver, lockfiles, bundlers, source maps, linting and formatting |
| L2 | Set up and configure a project with Vite, ESLint/Biome, Prettier, scripts and environment variables |
| L3 | Explain module resolution (ESM vs CommonJS, exports maps), tree shaking, code splitting, HMR, caching hashes, workspaces and task graphs |
| L4 | Diagnose bundle bloat, duplicate dependencies, broken source maps, cache misses and dependency conflicts |
| L5 | Design a repository's tooling: monorepo layout, shared configs, release process, build caching |
| L6 | Run tooling at scale: remote caches, CI speed and cost, dependency governance, tool migrations |
Packages and dependencies
npm, pnpm and the package manager's job
A package manager resolves a dependency graph from version ranges, downloads packages from a registry (npmjs.com, or a private one), installs them on disk, runs lifecycle scripts, and writes a lockfile. This is the same job Maven, Gradle, Cargo and Go modules do for their ecosystems (Vol. 1 ch. 2's package table).
| npm | pnpm | Yarn (Berry) | Bun | |
|---|---|---|---|---|
node_modules layout |
Hoisted, flat: deps of deps lifted to the top | Content-addressable store + symlinks: each package sees only its declared deps | Plug'n'Play (no node_modules), or the node-modules linker |
Hoisted (fast native installer) |
| Disk use | A copy per project | One global store, hard-linked: huge savings | PnP: zip archives | Global cache |
| Strictness | Phantom dependencies possible (you can import packages you didn't declare, because they were hoisted) | Strict: undeclared imports fail | Strict (PnP) | Like npm |
| Workspaces | ✓ | ✓ (pnpm-workspace.yaml, excellent filtering) |
✓ | ✓ |
| Lifecycle scripts | Run by default | Not run for dependencies by default (pnpm 10; allow-list them) | Configurable | Allow-list (trustedDependencies) |
Semantic versioning: MAJOR.MINOR.PATCH. A major bump breaks compatibility, a minor bump adds features compatibly, and a patch bump fixes bugs. Version ranges in package.json: ^1.4.2 (≥1.4.2 and <2.0.0, the default), ~1.4.2 (<1.5.0), 1.4.2 (exact), */latest (never). In 0.x versions the caret is narrower: ^0.4.2 means <0.5.0, since anything may break before 1.0.
Kinds of dependency: dependencies (needed at run time), devDependencies (build, test and lint only), peerDependencies (the host must provide it, as with React for a component library, which prevents two copies of React), and optionalDependencies. overrides (npm), pnpm.overrides and resolutions (Yarn) force a version deep in the tree, which you'll need for urgent security patches in transitive dependencies.
Lockfiles
A lockfile (package-lock.json, pnpm-lock.yaml, yarn.lock, bun.lock) records the exact resolved version and integrity hash of every package in the tree. It's the equivalent of Cargo.lock or go.sum, and Gradle's dependency locking.
- Commit it for applications and for monorepos.
- Install in CI with
npm ci/pnpm install --frozen-lockfile, which fail ifpackage.jsonand the lockfile disagree and never rewrite the lockfile. CI then builds exactly what was reviewed and tested, which makes builds reproducible. - Integrity hashes (SHA-512) mean a tampered tarball fails installation.
- Review lockfile diffs in PRs: unexpected new packages, or registry URLs that changed, are supply-chain red flags (chapter 28). Renovate and Dependabot automate updates in reviewable batches.
- Libraries publish without lockfiles (consumers resolve their own versions), but test against both the lowest and latest versions of their ranges.
Workspaces
Workspaces let one repository contain several packages that depend on each other, linked locally without publishing:
# pnpm-workspace.yaml
packages:
- "apps/*" # web, admin, docs
- "packages/*" # ui, api-client, config, utils
catalog: # pnpm catalogs: one place to pin shared versions across packages
react: ^19.2.0
typescript: ^5.9.0
// apps/web/package.json
{
"name": "@acme/web",
"dependencies": {
"@acme/ui": "workspace:*", // link to the local package; replaced by a real version on publish
"react": "catalog:"
}
}
$ pnpm --filter @acme/web dev # run in one package
$ pnpm --filter "...@acme/ui" build # build ui and everything that depends on it
$ pnpm -r --parallel lint # recursive across all packages
Workspaces give you atomic cross-package changes (change ui and web in one PR), one install and lockfile, and shared tooling configuration. A monorepo needs more than workspaces at scale: task orchestration and caching, which come later in this chapter.
Module systems
ESM and CommonJS
JavaScript has two module systems, and the interop between them is a long-running source of pain in the ecosystem:
| ES Modules (ESM) | CommonJS (CJS) | |
|---|---|---|
| Syntax | import x from "y", export const z |
const x = require("y"), module.exports = … |
| Standard | ECMAScript standard; native in browsers and Node | Node's original convention |
| Loading | Static structure (analysable, tree-shakable), async loading, top-level await |
Dynamic, synchronous require at run time |
| Bindings | Live bindings (importers see later changes to an exported let) |
A copy of module.exports at require time |
this, __dirname |
undefined; use import.meta.url, import.meta.dirname |
Available |
| File markers (Node) | .mjs, or .js with "type": "module" |
.cjs, or .js without "type": "module" |
The direction is clear: write ESM. Interop rules: ESM can import CJS (the default import gets module.exports, and named imports work when Node can detect them statically). CJS can require() ESM synchronously since Node 22 (require(esm), unflagged in Node 20.19+/22.12+), unless the module uses top-level await. Many libraries now ship ESM-only.
Package exports
The exports field in package.json defines a package's public entry points and conditional resolution. It replaced main, module and browser, and it encapsulates internals: deep imports that aren't listed fail.
{
"name": "@acme/ui",
"version": "3.2.0",
"type": "module",
"sideEffects": ["**/*.css"], // everything else can be tree-shaken (chapter 27)
"exports": {
".": {
"types": "./dist/index.d.ts", // TypeScript resolves this first ("types" must come first)
"import": "./dist/index.js", // ESM consumers
"require": "./dist/index.cjs" // CJS consumers (optional if ESM-only)
},
"./button": { "types": "./dist/button.d.ts", "default": "./dist/button.js" }, // subpath export
"./styles.css": "./dist/styles.css",
"./package.json": "./package.json"
},
"files": ["dist"], // only publish built output
"peerDependencies": { "react": "^18 || ^19" }
}
Conditions are matched in order: types, import, require, browser, node, deno, worker, react-server (RSC builds), development/production, and custom conditions. Tools such as publint and arethetypeswrong check that your exports, types and formats resolve correctly for every consumer. The dual-package hazard (CJS and ESM copies of the same package both loaded, so two instances with separate state, and instanceof failing) is another reason to go ESM-only where you can.
Bundlers and compilers
What a bundler does
A bundler takes your source (TypeScript, JSX, CSS, images, ESM imports across hundreds of files and packages) and produces optimised assets for browsers:
- Resolve the module graph from entry points (Node resolution,
exports, aliases). - Transform each module: TypeScript and JSX → JS, modern syntax → target syntax, CSS processing (PostCSS, Tailwind, CSS Modules), asset imports.
- Link and bundle: combine modules into chunks, with code splitting at dynamic imports and shared-chunk extraction.
- Optimise: tree shaking, minification (renaming, removing whitespace and dead code), scope hoisting, constant folding, CSS minification.
- Emit: content-hashed file names (
app.3f9a1c.js) for long-term caching (chapter 19), source maps, and a manifest mapping entries to output files (for SSR frameworks and preload hints).
In development, the job is different: fast startup and instant updates. Hot module replacement (HMR) swaps changed modules into the running app while keeping state.
Why bundle at all, when browsers support ESM? Thousands of unbundled modules mean thousands of requests and deep waterfalls of nested imports, plus no tree shaking across packages and no minification. Bundling remains the production default. Development servers increasingly serve unbundled or lightly bundled ESM for speed.
The tools
| Tool | Language | What it is | Used by |
|---|---|---|---|
| esbuild | Go | Extremely fast bundler + minifier + TS/JSX transpiler | Vite (dev pre-bundling and transforms, historically), Angular's builder, tsup, many CLIs |
| SWC | Rust | Fast compiler (TS/JSX → JS, minifier), a Babel replacement | Next.js, Deno, Rspack, Parcel, Jest (@swc/jest) |
| Babel | JS | The original plugin-based JS compiler | Legacy and plugin-heavy setups; the React Compiler ships as a Babel plugin (with SWC support arriving) |
| Rollup | JS (Rust parts) | ESM-first bundler with excellent tree shaking and plugin API | Vite production builds (historically), libraries |
| Rolldown | Rust | Rollup-compatible bundler by the Vite team (VoidZero), built on the Oxc toolchain | Vite 8's unified bundler (opt-in as rolldown-vite before that), replacing esbuild + Rollup |
| Vite | JS + native deps | Dev server (native ESM + HMR) + production build | The default for React, Vue, Svelte, Solid, Astro, SvelteKit, Nuxt, React Router, Angular dev server, Vitest |
| Webpack | JS | The long-time standard: configurable, huge plugin ecosystem, Module Federation | Legacy apps, CRA-era projects, complex enterprise configs |
| Rspack | Rust | Webpack-compatible API at 5–10× the speed | Migrating large Webpack codebases (ByteDance, Microsoft) |
| Turbopack | Rust | Incremental bundler with function-level caching | Next.js (default for dev and build) |
| Parcel | Rust/JS | Zero-config bundler | Smaller projects |
| Oxc | Rust | Parser, linter (oxlint), resolver, transformer and minifier toolkit | Rolldown, Vite, oxlint |
The trend through 2024–2026 is that JavaScript tooling is being rewritten in Rust and Go for 10–100× speedups: esbuild (Go), SWC, Rspack, Turbopack, Rolldown, Oxc and Biome (Rust), and the TypeScript compiler itself, rewritten in Go as TypeScript 7 (chapter 16). It's Vol. 1's "compiled native code versus an interpreted runtime" trade-off, applied to developer tools.
Vite in practice
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react({ babel: { plugins: ["babel-plugin-react-compiler"] } })],
server: { proxy: { "/api": "http://localhost:8080" } }, // dev proxy to a Spring/Go backend: no CORS
build: {
target: "es2022",
sourcemap: "hidden", // generate, but don't reference publicly (below)
rollupOptions: { output: { manualChunks: { charts: ["echarts"] } } },
},
define: { __APP_VERSION__: JSON.stringify(process.env.GIT_SHA) },
});
How Vite's dev server works. It serves your source as native ESM over HTTP and transforms each file on request (TS → JS), so startup is near-instant regardless of app size. Dependencies (node_modules) are pre-bundled once into single ESM files, which avoids hundreds of requests for libraries like lodash-es. HMR updates only the edited module and its boundary. Production builds bundle with Rollup or Rolldown for optimal output. Environment variables exposed to the client must be prefixed VITE_ (import.meta.env.VITE_API_URL). Anything in the client bundle is public, so never put secrets there.
Source maps
Production JavaScript is minified, bundled and transpiled, so a stack trace like app.3f9a1c.js:1:48213 is useless. A source map (.map JSON, version 3 format) maps each position in the output back to the original file, line, column and name, using Base64 VLQ-encoded segments.
- Debugging: DevTools load source maps automatically, so you set breakpoints in your original TypeScript.
- Error tracking: Sentry, Datadog and others symbolicate production stack traces using source maps you upload at build time (chapter 32).
- Privacy: public source maps expose your original source code. Options:
sourcemap: "hidden"(generate the maps, omit the//# sourceMappingURLcomment, upload them privately to your error tracker), serve them only to authenticated internal users, or accept that frontend code is effectively public anyway (minification isn't security). - Make sure maps match deployments exactly: tag them with the release or commit SHA (chapter 32's release health). Debug IDs (a newer standard) embed a unique ID in both the bundle and its map, so matching never fails.
- Keep source maps through every transformation step. Each tool (TS → Babel → bundler → minifier) must chain maps, or lines drift.
Code quality tooling
Dependency auditing
Covered as supply-chain security in chapter 28. The build-tooling checklist:
$ pnpm audit --prod # known vulnerabilities (GitHub Advisory DB) in runtime deps
$ npx npm-check-updates # what's outdated
$ npx knip # unused files, exports and dependencies (dead code + bloat)
$ pnpm why lodash # why is this in my tree?
$ npx publint && npx @arethetypeswrong/cli # (libraries) exports and types correctness
Automate with Renovate or Dependabot (grouped weekly PRs, automerge for patch-level devDependencies after CI passes), Socket or Snyk for behavioural and vulnerability analysis, and an SBOM per release. Treat npm audit output with judgement: many advisories concern build-time-only code paths. Prioritise runtime, internet-exposed paths.
ESLint
ESLint statically analyses JavaScript and TypeScript for bugs and code-quality problems. The modern flat config (eslint.config.js, the default since ESLint 9):
// eslint.config.js
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import react from "eslint-plugin-react";
import reactHooks from "eslint-plugin-react-hooks";
import jsxA11y from "eslint-plugin-jsx-a11y";
import importX from "eslint-plugin-import-x";
export default tseslint.config(
{ ignores: ["dist/**", "coverage/**"] },
js.configs.recommended,
...tseslint.configs.strictTypeChecked, // type-aware rules: no-floating-promises, no-unsafe-*, …
{ languageOptions: { parserOptions: { projectService: true } } },
reactHooks.configs.recommended, // rules of hooks + React Compiler diagnostics (chapter 22)
jsxA11y.flatConfigs.recommended, // accessibility (chapter 20)
{
plugins: { react, "import-x": importX },
rules: {
eqeqeq: "error",
"no-restricted-imports": ["error", { patterns: ["@acme/*/src/*"] }], // only public package entry points
"@typescript-eslint/no-floating-promises": "error", // forgotten awaits (chapter 15)
"import-x/no-cycle": "error",
},
},
);
High-value rules: type-aware TypeScript rules (no-floating-promises, no-misused-promises, no-unnecessary-condition, switch-exhaustiveness-check), react-hooks, jsx-a11y / Angular template accessibility, import boundaries (eslint-plugin-boundaries, Nx enforce-module-boundaries, chapter 21), and security (no-unsanitized from Mozilla for innerHTML sinks, chapter 28). Keep linting fast and actionable: errors that block CI, few warnings that everyone ignores. oxlint (Rust) runs hundreds of common rules 50–100× faster and is often used alongside ESLint for type-aware rules.
Prettier and Biome
Formatting is not linting. A formatter rewrites code into one canonical style, so code review never discusses spacing again (Go's gofmt and Rust's rustfmt established this culture).
- Prettier: the standard opinionated formatter for JS, TS, CSS, HTML, JSON, Markdown and YAML, with minimal options by design. Run it on save and in CI (
prettier --check), and turn off ESLint's stylistic rules (eslint-config-prettier). - Biome (Rust, the successor to Rome): formatter + linter in one fast binary, highly Prettier-compatible, with hundreds of lint rules. A single tool and config, often 10–30× faster. Its coverage of framework-specific rules (Angular templates, type-aware rules) is narrower, so some teams pair Biome for formatting and lint with ESLint for type-aware and framework rules.
Wire them into pre-commit hooks (lefthook or husky + lint-staged, running only on changed files) and CI. Add an .editorconfig for editors, and keep TypeScript's tsc --noEmit as a separate CI step, because type-checking isn't part of transpilation with esbuild or SWC.
Monorepos
Why monorepos
A monorepo keeps many projects (apps, libraries, services, sometimes frontend and backend) in one repository. Google, Meta, Microsoft and Uber famously use huge ones. Benefits: atomic cross-project changes (change an API and its consumers in one PR), shared tooling and configuration, one version of each dependency (no diamond-dependency drift), easy code sharing and refactoring, and visibility. Costs: tooling must scale (builds and tests can't run everything on every commit), CI design, ownership boundaries (CODEOWNERS), and repository size. The solution to the scaling costs is task graphs, affected detection and caching.
Task graphs
Monorepo tools model work as a directed acyclic graph (Vol. 1 ch. 3–4) of tasks, such as ui:build, web:build, web:test, api-client:typecheck, with edges from package dependencies and task dependencies. They then run tasks in topological order (chapter 4's topological sort), in parallel wherever the graph allows, using all CPU cores:
// turbo.json (Turborepo)
{
"$schema": "https://turborepo.com/schema.json",
"tasks": {
"build": { "dependsOn": ["^build"], "outputs": ["dist/**", ".next/**", "!.next/cache/**"], "inputs": ["src/**", "package.json", "tsconfig.json"] },
"test": { "dependsOn": ["build"], "outputs": ["coverage/**"] },
"lint": {},
"typecheck": { "dependsOn": ["^build"] },
"dev": { "cache": false, "persistent": true }
}
}
// "^build" = run build in my dependencies first (topological)
Affected builds
Affected detection runs tasks only for projects changed in this PR, plus everything that depends on them: the reverse-dependency closure of the changed files in the project graph. A one-line change in apps/docs shouldn't rebuild and retest the whole company.
$ npx nx affected -t lint test build --base=origin/main # Nx
$ npx turbo run test --filter="...[origin/main]" # Turborepo: changed packages + dependents
$ pnpm --filter "...[origin/main]" test # pnpm filtering
Accuracy depends on the graph being right. Undeclared dependencies (a package reading a file from another package by relative path, or a global config every task depends on) cause missed tests. Declare global inputs (root tsconfig, lockfile, .env schema) explicitly.
Caching
Computation caching is the biggest win. A task's result (its output files and terminal logs) is stored under a hash of all its inputs: source files, dependency outputs, the lockfile, environment variables, the command, the tool version. If the hash matches a previous run, the tool restores the outputs instead of running the task:
- Local cache: re-running the same build after switching branches is instant.
- Remote cache: shared across all developers and CI machines (Vercel Remote Cache, Nx Cloud, self-hosted). If CI built
ui@abc123once, every developer and every later pipeline gets it for free. CI times often fall from tens of minutes to a few minutes. - Correctness depends on declaring all inputs. A task that reads an undeclared environment variable or file can be served a wrong cached result (cache poisoning by omission). Turborepo's
env/globalEnv, Nx'sinputsandnamedInputsmake this explicit. Treat remote caches as security-sensitive: a writable shared cache is a supply-chain path, so restrict write access to trusted CI.
This is the same content-addressed idea as Git objects and Merkle trees (Vol. 1 ch. 3), applied to build outputs.
Turborepo
Turborepo (Vercel; rewritten in Rust) is a lightweight task runner layered on your package manager's workspaces: turbo.json pipelines, parallel execution, local and remote caching, --filter and affected runs, watch mode, and a TUI. It's minimal configuration and easy to adopt incrementally in a JS/TS monorepo. It doesn't generate code or enforce architecture beyond the task graph. Pair it with Changesets for versioning and publishing.
Nx
Nx is a full monorepo platform: a project graph inferred from code and package.json, plugins that understand frameworks (Angular, React, Next.js, Vite, Jest/Vitest, Playwright, Node, Go, Gradle and Maven for Java, .NET), generators (scaffold libraries and components consistently), migrations (nx migrate updates framework versions across the repo, like Angular's ng update), module boundary enforcement with tags (type:feature may depend on type:ui but not vice versa, chapter 21), affected commands, local and remote caching, and distributed task execution (splitting CI work across agents). Nx is particularly popular for large Angular monorepos and polyglot repos. It's more powerful than Turborepo, and more opinionated.
Bazel and polyglot build systems
Bazel (Google's open-sourced Blaze) is a language-agnostic, hermetic, reproducible build system for huge polyglot monorepos (Java, C++, Go, Rust, Python, JS, protobuf). Every build target declares exact inputs, tools run in sandboxes (undeclared files are invisible), outputs are content-addressed, and it offers remote execution (builds run on a cluster) and remote caching. It gives correctness and scale at the price of significant complexity: you write BUILD files (Starlark), and JS ecosystem integration (rules_js, aspect_rules_*) takes effort. Relatives include Buck2 (Meta, written in Rust), Pants, and Moon (a Rust-based, simpler polyglot task runner). Use Bazel-class tools when you have many languages and very large scale. Nx and Turborepo cover most JS/TS-centric monorepos.
| Turborepo | Nx | Bazel / Buck2 | |
|---|---|---|---|
| Model | Task runner over workspaces | Project graph + plugins + generators | Hermetic, declarative build graph |
| Languages | JS/TS-centric | JS/TS + plugins (Java/Gradle, Go, .NET…) | Any |
| Setup cost | Low | Medium | High |
| Caching | Local + remote | Local + remote + distributed execution | Local + remote cache + remote execution |
| Architecture enforcement | — | Module boundary tags | Visibility rules |
| Sweet spot | Small–medium JS monorepos | Medium–large, Angular/React enterprise | Very large polyglot orgs |
Releasing packages from a monorepo
For publishable packages (a design system, an SDK):
- Changesets: contributors add a small markdown "changeset" describing the change and its semver bump. A bot opens a "Version Packages" PR that bumps versions, updates dependents and writes changelogs, and merging it publishes.
- Conventional commits + semantic-release: versions are derived from commit messages (
feat:gives a minor bump,fix:a patch,BREAKING CHANGE:a major). - Nx Release has the same capabilities, built into Nx.
Publish with provenance and trusted publishing (chapter 28), and run publint before release.
Lab: the toolchain, measured
Run with npm 10, esbuild, Vite 8.3.5 (with its Rust-based Rolldown bundler) and Turborepo 2.11 on Node 22. The point of each experiment is to see what the tools actually do with your files, so their behaviour stops being magic.
Experiment 1: what one import costs
Three tiny modules, each using a single function from a popular library, bundled and minified with esbuild:
import _ from "lodash"; // a: the whole library as one CommonJS object
import { debounce } from "lodash-es"; // b: a named import from an ES-module build
import * as dates from "date-fns"; // c: a namespace import, but only dates.format is used
a 73844 bytes minified, 26444 gzipped
b 2928 bytes minified, 1463 gzipped
c 19650 bytes minified, 5688 gzipped
b shows tree shaking working: only debounce and its helpers survived. a couldn't be shaken because CommonJS exports are a runtime object the bundler can't analyse statically. c shows the bundler can shake a namespace import when it sees only dates.format used; most of the 19.6 KB is format itself, which supports every date token and locale. Measure before you trust a "lightweight" claim: Vite prints sizes per chunk, and rollup-plugin-visualizer or vite-bundle-analyzer draw the whole bundle as a treemap. Packages declare whether importing them has side effects ("sideEffects": false in package.json), which bundlers rely on to drop unused files entirely.
Experiment 2: a production build and a dev server
The shopping-list app from chapter 26, built with Vite 8 and source maps enabled:
$ npx vite build
✓ 15 modules transformed.
dist/index.html 0.29 kB │ gzip: 0.22 kB
dist/assets/index-Cs1vsncV.js 220.29 kB │ gzip: 68.97 kB │ map: 1,046.67 kB
✓ built in 596ms
$ npx vite
VITE v8.3.5 ready in 202 ms
Notice three things. The source map is about five times the size of the code it describes, which is fine because only DevTools and error trackers download it; but if you deploy it publicly, anyone can read your original source (many teams upload maps to their error tracker and don't serve them). The 220 KB is almost all React and React DOM; the app's own code is a few kilobytes, which is why framework choice dominates bundle size for small apps (chapter 24's islands experiment). And the dev server didn't bundle at all: it served each module as native ESM on request, transforming JSX on the fly, which is why it started in 0.2 s and why its startup doesn't grow with the size of your app.
Experiment 3: source maps in a stack trace
A function that throws for a negative price, bundled and minified with --sourcemap, run by Node with and without source-map support:
--- without source maps:
Error: negative price for Idli
at e (/tmp/V2/c30/sm/out.js:1:34)
--- with --enable-source-maps:
if (dish.price < 0) throw new Error(`negative price for ${dish.name}`);
Error: negative price for Idli
at priceWithGst (/tmp/V2/c30/sm/price.js:2:29)
The minified trace names a function e at column 34 of a single 235-byte line; the mapped trace names priceWithGst at line 2 of price.js and even prints the source line. Production error reports without uploaded source maps look like the first version, which is why release pipelines upload the maps for every build (chapter 32).
Experiment 4: a monorepo build cache, and the bug in the first attempt
Three workspace packages (@tiffin/money, @tiffin/ui which depends on it, and web which depends on both), each with a 1.5-second build, orchestrated by Turborepo with "dependsOn": ["^build"] (build dependencies first) and "outputs": ["dist/**"].
The first attempt cached nothing: every repeat build was a cache miss. The reason is instructive. Without a Git repository and .gitignore, Turborepo hashed every file in each package as an input, including the dist/ output and its own log file, so each build changed its own inputs and invalidated the next. Adding a .gitignore for dist, .turbo and node_modules (and initialising Git) fixed it:
=== first build
@tiffin/money:build: cache miss
@tiffin/ui:build: cache miss
web:build: cache miss
Time: 5.11s
=== build again, nothing changed
@tiffin/money:build: cache hit
@tiffin/ui:build: cache hit
web:build: cache hit
Time: 5ms >>> FULL TURBO
=== edit apps/web only
@tiffin/money:build: cache hit
@tiffin/ui:build: cache hit
web:build: cache miss
Time: 1.692s
=== edit packages/money (everything depends on it)
@tiffin/money:build: cache miss
@tiffin/ui:build: cache miss
web:build: cache miss
Time: 5.039s
Each task's cache key is a hash of its inputs (files, dependencies' hashes, environment variables you declare, the command). An unchanged repo restored all outputs from the cache in 5 ms; editing the app rebuilt only the app; editing the shared money package rebuilt everything downstream, in order. With a remote cache shared by the team and CI, a pull request often rebuilds only what it touched. Cache correctness depends on declaring inputs and outputs precisely: an undeclared environment variable that changes the build output gives you stale artefacts restored from cache, the worst kind of build bug.
Try it yourself
- Run
npx vite buildon a project you work on withrollup-plugin-visualizer. Which three dependencies are largest, and are you using most of each? - Find a dependency that ships both CommonJS and ES modules and read its
exportsfield inpackage.json. Which file does your bundler pick, and why? - Delete
package-lock.jsonandnode_modules, runnpm install, and diff the new lockfile against the old one. How many versions changed? - Add an environment variable to experiment 4's build output without declaring it in
turbo.json. Change it and rebuild. What does the cache restore?
Revision sheet: build tooling and monorepos
Key ideas
- Package managers (npm, pnpm, Yarn, Bun) resolve semver ranges into a dependency tree; pnpm's content-addressed store and strict
node_modulesprevent phantom dependencies. - Semver:
^minors and patches,~patches; lockfiles pin exact versions and integrity hashes;npm cifor reproducible installs. - Module systems: ESM (static, tree-shakeable, async) vs CommonJS (dynamic
require);package.jsonexports/importsmaps with conditions (import,require,browser,types); dual packages and their hazards. - Bundlers: dependency graph, transforms (TS/JSX via esbuild, SWC, Oxc), tree shaking, code splitting, minification, content hashing, CSS handling, asset pipelines; Vite (native-ESM dev server, Rolldown builds since Vite 8), Webpack/Rspack, Turbopack (Next.js), esbuild.
- Source maps: generated per build, uploaded to error trackers; decide whether to serve them publicly.
- Code quality: ESLint (flat config) / Biome / oxlint, Prettier or Biome formatting, TypeScript type-checking in CI, pre-commit hooks.
- Monorepos: workspaces; task graphs (
dependsOn); content-hash caching (local and remote); affected-only builds; Turborepo, Nx, Bazel; versioning and publishing with Changesets. - Native tooling trend: Go and Rust rewrites (esbuild, SWC, Rolldown, Oxc, Biome, Turbopack, TypeScript 7) for large speedups.
Numbers to remember
- Lab:
lodashdefault import 26.4 KB gzipped vslodash-esnamed import 1.5 KB. - Lab: a React shopping list built to 220 KB (69 KB gzipped); the source map was about 1 MB; Vite's dev server ready in 0.2 s.
- Lab: monorepo rebuild with nothing changed: 5 ms from cache vs 5 s.
Pitfalls
- Not committing lockfiles;
npm installin CI; mixing package managers. - CommonJS-only or side-effectful dependencies defeating tree shaking; barrel files re-exporting everything.
- Secrets in client-side environment variables (
VITE_,NEXT_PUBLIC_values are public). - Cache keys missing inputs (environment variables, generated files) or including outputs.
- Duplicate copies of React or other singletons from mismatched versions.
- Publicly served source maps exposing proprietary source.
Glossary
- Semver range: a version constraint like
^1.2.3. - Lockfile: the exact resolved dependency tree with integrity hashes.
- Tree shaking: dead-code elimination based on static ES module imports and exports.
- HMR: hot module replacement, updating a running page's modules without a reload.
- Exports map: the
exportsfield controlling which files a package exposes under which conditions. - Remote cache: a shared store of task outputs keyed by input hashes.