Build Only Affected Projects with Nx
Let Nx compute the affected graph from the changed files, run only affected targets in CI, and cache outputs so untouched projects are never rebuilt.
Task
Reduce CI time by running tasks only for projects affected by a change.
When to use this
CI rebuilds and retests every package on every commit, so a one-line change takes as long as a full rebuild and review is slow.
Prerequisites
- An Nx workspace
- A CI job that knows the base commit
Steps
1. Run affected targets against the base of the branch.
Expected output: Only changed and dependent projects run.
2. Configure a remote cache so outputs are shared across CI and developers.
Expected output: Repeat tasks are not recomputed.
3. Ensure project graphs declare dependencies accurately.
Expected output: Affected computation is correct.
4. Guard against a missed dependency by periodically running the full suite.
npx nx affected -t build test --base=origin/mainExpected output: Correctness is not sacrificed for speed.
Troubleshooting
Problem
Affected set misses a change
Solution
Incorrect project graph inputs or unmodeled implicit dependencies cause misses; declare them explicitly.
Problem
Cache serves stale output
Solution
Cache keys must include the relevant inputs; review the target configuration when outputs are stale.
Limitations
- Affected builds rely on an accurate project graph; undocumented implicit dependencies cause misses.
- Remote caching stores build outputs that may include sensitive artifacts if not configured carefully.
Context
Reduce CI time by running tasks only for projects affected by a change. CI rebuilds and retests every package on every commit, so a one-line change takes as long as a full rebuild and review is slow.
Steps
- Run affected targets against the base of the branch. Expected: Only changed and dependent projects run.
- Configure a remote cache so outputs are shared across CI and developers. Expected: Repeat tasks are not recomputed.
- Ensure project graphs declare dependencies accurately. Expected: Affected computation is correct.
- Guard against a missed dependency by periodically running the full suite. Expected: Correctness is not sacrificed for speed.
npx nx affected -t build test lint \
--base=origin/main \
--head=HEAD \
--parallel=4
Verify
- Only changed and dependent projects run.
- Repeat tasks are not recomputed.
- Affected computation is correct.
- Correctness is not sacrificed for speed.
Limits
- Affected builds rely on an accurate project graph; undocumented implicit dependencies cause misses.
- Remote caching stores build outputs that may include sensitive artifacts if not configured carefully.