Turborepo & Nx
Package-manager workspaces link packages and run scripts across them. Once a monorepo has dozens of packages, two more problems dominate CI time: running tasks in the right order in parallel, and not running tasks whose inputs haven't changed. Turborepo and Nx are task runners that sit on top of npm, Yarn or pnpm workspaces and solve exactly those.
Note: Neither tool is in this course's offline registry, so this lesson is an overview with configuration examples and a runnable model of their core idea. The workspace features they build on were all shown live in the npm, Yarn and pnpm lessons.
The core idea: a cached task graph
Both tools see the monorepo as a graph of tasks: ui#build depends on core#build, app#test depends on app#build, and so on. For each task they compute a hash of its inputs:
- the package's source files (or a declared subset),
- the hashes of the tasks it depends on,
- the relevant lockfile entries, environment variables and the task's command.
If a task with the same hash ran before, its outputs (dist/, coverage, logs) are restored from the cache and the command isn't run at all. That cache can be local or remote, shared by the whole team and CI, so a pull request that only touches docs rebuilds only docs, even on a fresh CI machine.
// A model of a cached task runner: hash inputs + dependency hashes, skip on cache hit.
const hash = (s) => [...s].reduce((h, c) => (h * 33 + c.charCodeAt(0)) >>> 0, 5381).toString(16);
const packages = {
core: { deps: [], src: 'export const add = (a, b) => a + b;' },
ui: { deps: ['core'], src: 'import { add } from "core"; export const Button = () => add(1, 1);' },
app: { deps: ['ui'], src: 'import { Button } from "ui"; Button();' },
docs: { deps: [], src: '# Docs' },
};
const cache = new Map();
function run(label) {
const done = {};
const build = (name) => {
if (done[name]) return done[name];
const depHashes = packages[name].deps.map(build);
const key = hash(packages[name].src + depHashes.join(','));
const status = cache.has(key) ? 'cache hit, replayed' : 'executed';
cache.set(key, `dist of ${name}`);
console.log(` ${(name + '#build').padEnd(11)} ${key.padStart(8)} ${status}`);
return (done[name] = key);
};
console.log(label);
Object.keys(packages).forEach(build);
}
run('first run:');
run('second run, nothing changed:');
packages.ui.src += ' // tweak';
run('after editing ui:');first run:
core#build f944ad8 executed
ui#build 1ca01d92 executed
app#build f8e9ad32 executed
docs#build 5bedd211 executed
second run, nothing changed:
core#build f944ad8 cache hit, replayed
ui#build 1ca01d92 cache hit, replayed
app#build f8e9ad32 cache hit, replayed
docs#build 5bedd211 cache hit, replayed
after editing ui:
core#build f944ad8 cache hit, replayed
ui#build 1304172c executed
app#build 17f92412 executed
docs#build 5bedd211 cache hit, replayed
Editing ui changed its hash, and because app's hash includes ui's, app rebuilt too; core and docs came from the cache. The Build Fundamentals course covers cache keys and hermeticity in depth.
Turborepo
Turborepo (Vercel) is deliberately small: one turbo.json at the root describes tasks; everything else stays in your package manager's workspace.
{
"$schema": "https://turborepo.com/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"inputs": ["src/**", "package.json", "tsconfig.json"],
"outputs": ["dist/**"]
},
"test": { "dependsOn": ["build"], "outputs": ["coverage/**"] },
"lint": {},
"dev": { "cache": false, "persistent": true }
}
}| Syntax | Meaning |
|---|---|
"dependsOn": ["^build"] |
run build in all dependencies first (the ^) |
"dependsOn": ["build"] |
run this package's own build first |
outputs |
what to store in and restore from the cache |
"cache": false, persistent |
for dev servers and watchers |
npx turbo run build test # whole graph, parallel, cached
npx turbo run build --filter=@acme/web... # web and its dependencies (pnpm-style filters)
npx turbo run test --affected # only packages changed versus the base branch
npx turbo login && npx turbo link # enable the remote cache (Vercel, or a self-hosted server)Output of a second, unchanged run shows cache hit, replaying logs for each task and a FULL TURBO summary.
Nx
Nx (Nrwl) does the same at its core and adds a lot around it: project graph visualisation (nx graph), generators that scaffold code, plugins that infer tasks from tool configs (Vite, Jest, Playwright…), module-boundary lint rules, and distributed task execution in CI.
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"targetDefaults": {
"build": { "dependsOn": ["^build"], "inputs": ["production", "^production"], "outputs": ["{projectRoot}/dist"], "cache": true },
"test": { "inputs": ["default", "^production"], "cache": true }
},
"namedInputs": {
"default": ["{projectRoot}/**/*"],
"production": ["default", "!{projectRoot}/**/*.test.ts"]
}
}npx nx run-many -t build test # all projects
npx nx affected -t test # only what the current branch affects
npx nx graph # interactive dependency graph in the browsernamedInputs let a test-file change skip production builds of dependents, a finer-grained version of Turborepo's inputs.
Choosing
| Need | Choice |
|---|---|
| a few packages, simple scripts | your package manager alone (pnpm -r, yarn workspaces foreach -t) |
| fast CI with caching, minimal setup | Turborepo |
| a large org monorepo: generators, boundaries, distributed CI, many frameworks | Nx |
| a polyglot monorepo (Go, Java, Python and JS together) with hermetic builds | Bazel (see the Bazel course) |
Whatever you choose, the caching only works if tasks are deterministic and declare their inputs and outputs honestly. A build that embeds the current time, or reads an undeclared environment variable, produces cache hits with the wrong content.
Test yourself
In turbo.json, what does "dependsOn": ["^build"] mean?
- Run build after this package's tests
- Run the build task of this package's dependencies first
- Never cache build
- Build only changed files
Why did app#build re-run in the model after only ui changed?
- The cache was cleared
- app's task hash includes the hash of its dependency ui#build
- app always runs
- docs changed too
What breaks a task cache?
- Using pnpm
- Non-deterministic builds or undeclared inputs, such as embedding the current time or reading an unlisted env var
- Remote caching
- Having more than ten packages