Configuring CI Using Circle CI and Nx

Below is an example of a Circle CI setup, building, and testing only what is affected.

.circleci/config.yml
1version: 2.1 2 3orbs: 4 nx: nrwl/nx@1.6.2 5 6jobs: 7 main: 8 docker: 9 - image: cimg/node:lts-browsers 10 steps: 11 - checkout 12 13 # This enables task distribution via Nx Cloud 14 # Run this command as early as possible, before dependencies are installed 15 # Learn more at https://nx.dev/ci/reference/nx-cloud-cli#npx-nxcloud-startcirun 16 # Connect your workspace by running "nx connect" and uncomment this line to enable task distribution 17 # - run: npx nx start-ci-run --distribute-on="3 linux-medium-js" --stop-agents-after="build" 18 19 - run: npm ci --legacy-peer-deps 20 - nx/set-shas: 21 main-branch-name: 'main' 22 23 # Prepend any command with "nx-cloud record --" to record its logs to Nx Cloud 24 # - run: npx nx-cloud record -- echo Hello World 25 - run: 26 command: npx nx affected -t lint test build 27 # Nx Cloud recommends fixes for failures to help you get CI green faster. Learn more: https://nx.dev/ci/features/self-healing-ci 28 - run: 29 command: npx nx fix-ci 30 when: always 31 32workflows: 33 version: 2 34 35 ci: 36 jobs: 37 - main 38

Get the Commit of the Last Successful Build

CircleCI can track the last successful run on the main branch and use this as a reference point for the BASE. The Nx Orb provides a convenient implementation of this functionality, which you can drop into your existing CI workflow. Specifically, for push commits, nx/set-shas populates the $NX_BASE environment variable with the commit SHA of the last successful run.

To understand why knowing the last successful build is important for the affected command, check out the in-depth explanation in Orb's docs.

Using CircleCI in a private repository

To use the Nx Orb with a private repository on your main branch, you need to grant the orb access to your CircleCI API. Create an environment variable called CIRCLE_API_TOKEN in the context of the project.

Caution

It should be a user token, not the project token.