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

Workbench / Volume 2 Exercises: The Web Frontend

V2·30

Build Tooling and Monorepos

Exercises for Volume 2, chapter 30: npm, pnpm and the package manager's job; version ranges, lockfiles and workspaces; ESM and CommonJS; package exports; what a bundler does, the tools, Vite in practice, and source maps; dependency auditing, ESLint, Prettier and Biome; and monorepos: why, task graphs, affected builds, caching, Turborepo, Nx, Bazel, and releasing packages. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~13 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. The measured exercises use Node 22.22, npm 10, pnpm 10.34, the semver package npm itself uses, Vite 8.3.8, esbuild 0.25 and Turborepo 2.11.10, run on the lab's three-package monorepo. Every quoted output is real. Four of them catch teams out:

  • P1: ^0.2.3 does not accept 0.3.0.
  • P2: code that requires a package it never declared works under npm and fails under pnpm.
  • P3: one package loaded once as ESM and once as CommonJS produced two Money classes, so instanceof returned false.
  • P6: Vite put a secret into the client bundle because someone named it VITE_RAZORPAY_SECRET.

The chapter's lab measured import costs (lodash 73,844 B vs lodash-es 2,928 B), a Vite 8 build (220 KB of JS, of which React is nearly all, and a 1 MB source map), source-mapped stack traces, and a Turborepo cache that only started hitting once dist/ was ignored. Its builds went from 5.11 s to 5 ms when nothing changed, 1.69 s when only the app changed, and 5.04 s when the shared package changed. The exercises build on those.

Coverage map.

Chapter component Exercises
npm, pnpm and the package manager's job T1, P2
version ranges, lockfiles T1, P1
workspaces T2, P7
ESM and CommonJS T3, P3
package exports T3, P3
what a bundler does; the tools T4, P4
Vite in practice; environment variables T5, P6
source maps T5, P5
dependency auditing T6
ESLint, Prettier and Biome T6, P8
why monorepos; task graphs; affected builds T7, P7
caching; Turborepo; Nx T8, P7
Bazel and polyglot build systems T9
releasing packages from a monorepo T9, P9

Theory

T1. Package managers, version ranges and lockfiles

  1. What does a package manager do (resolve versions, download and verify tarballs, lay out node_modules, run scripts, write a lockfile)? Compare npm, pnpm and Yarn (Berry, Plug'n'Play) on layout, disk usage, speed and strictness.
  2. P1 evaluated ranges against nine versions: ^0.2.3 matched only 0.2.3 and 0.2.9 (not 0.3.0); ^1.2.3 matched 1.2.3, 1.2.9 and 1.9.0 (not 2.0.0); ~1.2.3 matched only 1.2.x; prereleases (1.3.0-beta.1, 1.2.4-rc.1) matched no range unless includePrerelease was set. Explain semver ranges and why caret behaves differently below 1.0.0.
  3. Why commit a lockfile, why install with npm ci in CI, and what's the difference between a lockfile for an application and for a library?

T2. Workspaces and dependency hygiene

  1. Explain workspaces (npm, pnpm, Yarn): multiple packages in one repository, linked locally, one lockfile, workspace: protocol (pnpm/Yarn), hoisting and filtering (pnpm --filter web build).
  2. P2's phantom dependency: a file that required ms (a dependency of debug, not declared) worked under npm's hoisted layout (7200000 ms) and failed under pnpm's strict layout with Cannot find module 'ms', while the declared debug worked in both. Why are phantom dependencies dangerous, and how do you detect them under npm?
  3. Explain dependencies, devDependencies, peerDependencies (and peerDependenciesMeta.optional), optionalDependencies, overrides/resolutions, and when each applies in a monorepo of an app and two internal libraries.

T3. ESM, CommonJS and package exports

  1. Compare ES modules and CommonJS: syntax, static vs dynamic loading, live bindings vs copied values, top-level await, __dirname vs import.meta, file extensions and "type": "module". What did Node 22's require(esm) change? (P3: require('./esm-only.mjs') returned the module's exports.)
  2. P3's dual-package hazard: tb-money shipped ESM and CJS builds via exports conditions; the app imported it as ESM while a legacy CJS module required it, and both copies were evaluated: an object created by the CJS copy wasn't instanceof the ESM Money, and a registry set through one copy wasn't visible in the other. Explain, and the ways to avoid it.
  3. P3: deep imports not listed in exports failed with ERR_PACKAGE_PATH_NOT_EXPORTED (the same error this chapter's environment produced for @testing-library/user-event/package.json in chapter 26's setup). Write an exports map for @tiffin/ui with conditions (types, import, require, browser, development), subpaths for components, and ./package.json, and explain condition ordering.

T4. What a bundler does, and the tools

  1. List a bundler's jobs: resolve imports, transform (TypeScript, JSX, CSS), build a module graph, tree-shake, split chunks, minify, hash file names, emit source maps, handle assets, and inject environment values. The lab: Vite's 220 KB bundle was almost all React; the app's code was a few KB.
  2. Compare the tools: webpack (mature, plugin ecosystem), Rollup (library-oriented ESM output), esbuild (Go, very fast), SWC (Rust compiler), Rolldown (Rust Rollup-compatible bundler, used by Vite 8), Rspack (Rust webpack-compatible), Turbopack (Next.js), Parcel, Bun's bundler. How do you choose for an app vs a library?
  3. Explain code splitting strategies (route-based, dynamic import(), vendor chunks, manualChunks), content hashing for caching (chapter 19's T3), and the trade-off between many small chunks and a few big ones under HTTP/2.

T5. Vite in practice, environment variables and source maps

  1. Explain Vite's two modes: the dev server (native ESM served on demand, esbuild/Oxc transforms, dependency pre-bundling, HMR: the lab started in 202 ms) and the production build (bundled with Rolldown). Why can something work in dev and break in the build (CommonJS interop, case-sensitive paths, env variables, dynamic imports with variables)?
  2. P6: with .env containing VITE_API_URL, RAZORPAY_SECRET and VITE_RAZORPAY_SECRET, the built bundle contained https://api.tiffinbox.in and rzp_live_OOPS456 but not rzp_live_SECRET123 (it became void 0). Explain Vite's env handling (import.meta.env, the VITE_ prefix, modes, .env.[mode]), why it's a security boundary, and how to keep secrets out of bundles.
  3. The lab: the source map was about 5× the code (1,046 KB for 220 KB) and the mapped stack trace showed priceWithGst at price.js:2:29 instead of e at out.js:1:34. How should production handle source maps (hidden maps uploaded to the error tracker, not served publicly), and what about sourcesContent and debug IDs?

T6. Dependency auditing, ESLint, Prettier and Biome

  1. Chapter 28 covered npm audit triage and supply-chain defences. What else belongs in dependency hygiene (outdated reports, licence checks, duplicate packages in the bundle, unused dependencies with knip), and how often should it run?
  2. Explain ESLint's flat config (eslint.config.js), rule categories (possible problems, suggestions, style), plugins (typescript-eslint with type-aware rules like no-floating-promises, react-hooks, jsx-a11y, import/boundaries), and why formatting rules don't belong in ESLint any more.
  3. Compare Prettier and Biome (formatter + linter in one Rust binary) on speed, rule coverage, ecosystem and migration. P8 asks you to measure both on your repo. What's the role of editor integration, pre-commit hooks (lint-staged) and CI?

T7. Monorepos, task graphs and affected builds

  1. Why monorepos (atomic changes across packages, shared tooling, one version of dependencies, code reuse, easier refactors) and their costs (CI time, tooling, ownership, permissions, repo size)? Compare with polyrepos for TiffinBox's customer app, partner portal, design system and shared packages.
  2. Explain the task graph: tasks (build, test, lint) per package, with dependencies ("dependsOn": ["^build"]: build dependencies first) forming a DAG that tools execute in parallel where possible. The lab's three packages built in order (money → ui → web, 5.11 s).
  3. Affected builds: run tasks only for packages changed since a base commit and their dependents (turbo run test --filter=...[origin/main], nx affected -t test). The lab: editing only apps/web rebuilt only web (1.69 s); editing packages/money rebuilt all three (5.04 s). What can make affected detection wrong (root config files, global inputs, generated code, implicit dependencies)?

T8. Caching, Turborepo and Nx

  1. Explain task caching: the cache key (hash of input files, dependencies' hashes, the command, declared environment variables, tool versions), outputs restored on hit, logs replayed, and remote caching shared by CI and developers. The lab's first attempt never hit because dist/ and .turbo logs were hashed as inputs.
  2. P7 built web with API_URL=https://staging.api and then https://prod.api without declaring the variable: the build output said API_URL="unset" both times, and the second run was a cache hit. After adding "env": ["API_URL"], each value produced a different hash and the correct output, and returning to staging hit its own cache entry. Explain Turborepo 2's strict environment mode and why undeclared inputs make caches wrong.
  3. Compare Turborepo and Nx (task orchestration, caching, affected, code generators, project graph inference, module boundaries, plugins for frameworks, distributed task execution) and when you'd pick each for TiffinBox.

T9. Bazel and releasing packages

  1. When do polyglot build systems (Bazel, Buck2, Pants) make sense (many languages, hermetic and reproducible builds, very large repos, remote execution), and what do they cost (rules for each language, steep learning curve, fighting the JavaScript ecosystem's conventions)?
  2. How do you version and release packages from a monorepo: fixed vs independent versioning, Changesets (a changeset file per PR, generated changelogs, version PRs), semantic-release, Nx release, and publishing with provenance (chapter 28's T7)?
  3. For internal-only packages (@tiffin/money, @tiffin/ui), do you need to publish at all? Compare "internal packages compiled by the app" (just-in-time, exports pointing at source), "built packages" (each builds to dist), and publishing to a private registry.

Programming exercises

P1. Version ranges, tested

Use the semver package to evaluate ^0.2.3, ~0.2.3, ^1.2.3, ~1.2.3, 1.x, >=1.2.3 <2, * and 1.2.3 against 0.2.3, 0.2.9, 0.3.0, 1.2.3, 1.2.9, 1.9.0, 2.0.0, 1.3.0-beta.1 and 1.2.4-rc.1. Then audit your app's package.json: find ^0.x dependencies that will never get minor updates automatically, exact pins without reason, and * or latest ranges, and fix them.

P2. Phantom dependencies, npm vs pnpm

Install debug (which depends on ms) with npm, write a file that requires ms without declaring it, and run it. Repeat in a separate folder with pnpm. Then run knip or import/no-extraneous-dependencies on your app to find real phantom imports, and decide whether to move the repo to pnpm.

P3. The dual-package hazard and exports

Create a local package with exports conditions pointing import at an ESM file and require at a CJS file, each defining a Money class and a registry Map. Import it as ESM in an app that also loads a legacy CJS module which requires it. Check instanceof and the registry, try deep imports of unexported files, and require an ES module. Then fix the hazard two ways.

P4. Inspect what the bundler produced

Build your app with a bundle analyzer (rollup-plugin-visualizer, vite-bundle-analyzer, or esbuild's --metafile with the analyzer): list chunks, their sizes (raw and gzip), the largest modules, duplicated packages, and code that's in the initial chunk but only used on one route. Fix two problems and compare before and after.

P5. Source maps in production

Build with hidden source maps, upload them to an error tracker (Sentry or a local symbolication step with source-map's SourceMapConsumer), throw an error in production code, and compare the raw and symbolicated stack traces. Check that the deployed site doesn't serve .map files publicly and that the bundle has no sourceMappingURL comment.

P6. Keep secrets out of client bundles

In a Vite app, create .env with VITE_API_URL, RAZORPAY_SECRET and a mistakenly named VITE_RAZORPAY_SECRET. Reference all three via import.meta.env, build, and grep the bundle. Then add a CI check that fails the build if bundles contain secret patterns, and move the secret's use to a server route.

P7. Turborepo caching with environment variables and affected runs

Using the lab's three-package monorepo, make web's build write process.env.API_URL into its output. Build with two different values without declaring the variable, then with "env": ["API_URL"]. Then run turbo run build --filter=...[HEAD^] after changing only packages/ui, and add globalDependencies for tsconfig.base.json.

P8. Lint and format: ESLint, Prettier and Biome

Configure ESLint flat config with typescript-eslint (type-aware), react-hooks and jsx-a11y; add Prettier. Measure lint and format times on your repo. Then try Biome (biome check), compare time and findings, and decide on the setup. Add lint-staged for pre-commit and a CI job. Show one real bug each tool catches.

P9. Release internal packages with Changesets

In the monorepo, make @tiffin/money and @tiffin/ui publishable to a private registry (Verdaccio locally): exports maps (T3), types, files, publishConfig, workspace:* dependencies. Add Changesets: create changesets in two PRs (a patch to money and a minor to ui), run changeset version, check that ui's dependency range on money was updated and changelogs written, and publish with changeset publish from CI with provenance.

Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–30)

C1. Set up the TiffinBox frontend monorepo

Create the monorepo: pnpm workspaces; apps (Next.js customer app, Angular partner portal, Storybook for the design system); packages (ui design system with tokens, money, api-client generated from OpenAPI, schemas with Zod, i18n, eslint-config, tsconfig); Nx or Turborepo with build, test, lint, typecheck tasks, dependsOn, inputs/outputs and env declared, remote caching, affected runs in CI, module boundaries (chapter 21's P7), Changesets for packages consumed outside the repo, Renovate, and size budgets. Measure CI time for a typical PR before and after caching.

Combines: UI architecture and boundaries (ch 21), React and Angular (ch 22, 23), full-stack frameworks (ch 24), testing in CI (ch 26), performance budgets (ch 27), supply-chain security (ch 28) and this chapter.

C2. Migrate a webpack app to Vite (or Rspack)

The partner portal's legacy React admin is a webpack 4 app with Babel, CommonJS imports, process.env.* everywhere, custom loaders (SVG as React components, Markdown), require.context for locale files, and a 4-minute build. Migrate to Vite (or Rspack if webpack-compatibility matters), keeping behaviour identical. Measure dev start, HMR latency, build time and bundle size before and after.

Combines: JavaScript modules (ch 15), TypeScript (ch 16), performance and bundle size (ch 27), testing before refactors (ch 26) and this chapter.

C3. A reproducible, secure build pipeline

Design the frontend build pipeline end to end: pinned Node and package manager versions (packageManager + Corepack, .nvmrc), frozen lockfile installs, install scripts allow-listed, cached and affected builds with declared inputs, deterministic outputs (verify by rebuilding and diffing), hidden source maps uploaded per release, bundle secret scanning, SBOM generation (CycloneDX), provenance for published packages, and artefact promotion (the same built artefact goes to staging then production). Document how to rebuild any release.

Combines: Volume 1's CI/CD and release practices (ch 10), supply-chain security (ch 28), testing (ch 26) and this chapter.

What the chapter leaves out

TypeScript project references and build performance

Large TypeScript monorepos use project references (composite: true, references in tsconfig, tsc --build) so each package type-checks once and emits declaration files consumers reuse, plus isolatedDeclarations (fast .d.ts generation without full type-checking), incremental builds, and faster type-checkers on the horizon (the TypeScript native port, tsgo, aiming for roughly 10× faster checks). Without them, every app type-checks every package's source, and tsc becomes the slowest step in CI.

Module federation and micro-frontend builds

Module Federation (webpack 5, Rspack, Vite plugins) lets separately built apps load each other's modules at runtime, sharing dependencies like React as singletons. It enables independent deployments of parts of a page (chapter 21's gaps) at the cost of runtime version negotiation, harder debugging and cross-team contracts. Native Federation (Angular) and import maps offer standards-based alternatives.

Git at monorepo scale

Large monorepos need Git features and tools: sparse checkouts (git sparse-checkout), partial clones (--filter=blob:none), shallow fetches in CI, git maintenance, filesystem monitors (core.fsmonitor), Scalar for very large repos, and merge queues to keep main green when many PRs land. CODEOWNERS and branch protection give per-directory ownership.

Build observability

Treat CI as a system to monitor: task durations and cache hit rates per task (Turborepo's --summarize, Nx Cloud analytics), flaky task tracking, the slowest packages, install time, and cost. A dashboard of "time from push to green" per team often reveals one misconfigured task (an undeclared input causing misses, like the lab's first attempt) wasting hours a day.

Alternative runtimes and toolchains

Bun (runtime, package manager, bundler and test runner in one, fast installs) and Deno (secure-by-default runtime with built-in tooling, npm compatibility, JSR registry) offer integrated toolchains; Oxc (Rust JS tools: parser, linter oxlint, resolver, transformer) powers parts of Vite's new stack; Rolldown, Rspack and Turbopack are replacing older JavaScript-based bundlers. Evaluate on compatibility with your frameworks and CI, not benchmarks alone.

Senior exercises

S1. Choose the package manager and monorepo tool

TiffinBox's frontends live in four repos with npm, different ESLint configs, two React versions and duplicated API clients. Write the decision: monorepo or not, npm vs pnpm vs Yarn, Turborepo vs Nx (vs Bazel), migration plan, risks and success metrics.

S2. Review a build configuration pull request

A PR changes the build: adds "*" ranges for three new dependencies; sets build.sourcemap: true and deploys maps; adds VITE_SENTRY_AUTH_TOKEN to .env; disables the lockfile in CI with npm install --no-package-lock "because of conflicts"; adds a Turborepo build task without outputs and with an undeclared API_URL; and adds postinstall: "node scripts/patch.js" that edits files in node_modules. Write the review.

S3. Make CI fast without making it wrong

The frontend monorepo's PR pipeline takes 28 minutes; developers batch changes and skip running tests locally. Diagnose and plan improvements: affected detection, remote caching, task parallelism and distribution, test splitting, E2E sharding, install caching, and verifying cache correctness. Set targets and metrics.

S4. Plan the move from CommonJS to ESM for internal packages

Internal packages are CommonJS with main fields; some consumers are Node services (via require), others are bundled apps. You want ESM-only packages with exports. Plan the migration: Node version requirements (require(esm)), TypeScript settings (module: nodenext, verbatimModuleSyntax), dual-package hazards (P3), exports maps, test runners, and a rollout order.

S5. Teach build tooling with four surprising outputs

Prepare a 20-minute session for new frontend engineers using P1 (^0.2.3 excludes 0.3.0), P2 (phantom dependency works in npm, fails in pnpm), P6 (a VITE_-prefixed secret in the bundle) and P7 (an undeclared env var gives the wrong cached build). For each: the demo, why it happens, and the rule. End with five rules.