How to Build Only Affected Projects With nx affected in CI
nx affected --target=test walks the project graph from the changed files and runs the target only on affected projects plus everything that depends on them.
Nx computes an affected set from the diff between a base and head SHA, then runs a target across just those projects. Set the base to the PR base (or the last successful commit) so the graph traversal is correct.
Steps
- Checkout with
fetch-depth: 0so both base and head are available. - Set the base and head SHAs (nrwl/nx-set-shas helps on push).
- Run
npx nx affected -t <target> --base=$BASE --head=$HEAD.
Workflow
.github/workflows/ci.yml
jobs:
affected:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- uses: actions/setup-node@v4
with: { node-version: 20 }
- run: npm ci
- uses: nrwl/nx-set-shas@v4
- run: npx nx affected -t lint test build --base=$NX_BASE --head=$NX_HEADGotchas
- Affected is dependency-aware: it includes projects that depend on the changed one, which is what keeps skipping correct.
- A wrong base (for example the default
mainon a stale branch) can under- or over-select projects; pin it with nx-set-shas.
Related guides
How to Run Only Affected Packages With turbo --filter in CIUse turbo run with a git-based --filter to build only the packages changed since a base ref in a Turborepo, s…
How to Build a Dynamic Matrix From Changed DirectoriesGenerate a GitHub Actions job matrix at runtime from the directories that changed, using fromJSON so only aff…
How to Skip Work Safely With Dependency-Aware SelectionKeep incremental CI correct by including dependents when you skip, so a change to a shared module still re-te…