Configuring CI Using CircleCI and Nx

The CircleCI can track the last successful run on main branch and use this as a reference point for the BASE. The Nx Orb provides convenient implementation of this functionality which you can drop into you existing CI config. To understand why knowing the last successful build is important for the affected command, check out the in-depth explanation at Orb's docs.

Below is an example of a Circle CI setup for an Nx workspace only building and testing what is affected. For more details on how the orb is used, head over to the official docs.

1version: 2.1
2orbs:
3  nx: nrwl/nx@1.5.1
4jobs:
5  main:
6    docker:
7      - image: cimg/node:lts-browsers
8    steps:
9      - checkout
10      - run: npm ci
11      - nx/set-shas
12
13      - run: npx nx workspace-lint
14      - run: npx nx format:check
15      - run: npx nx affected --base=$NX_BASE --head=$NX_HEAD --target=lint --parallel=3
16      - run: npx nx affected --base=$NX_BASE --head=$NX_HEAD --target=test --parallel=3 --ci --code-coverage
17      - run: npx nx affected --base=$NX_BASE --head=$NX_HEAD --target=build --parallel=3
18workflows:
19  build:
20    jobs:
21      - main
22

The pr and main jobs implement the CI workflow.

Using CircleCI on 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. You can do this by creating an environment variable called CIRCLE_API_TOKEN in the context or the project.

Distributed CI with Nx Cloud

In order to use distributed task execution, we need to start agents and set the NX_CLOUD_DISTRIBUTED_EXECUTION flag to true.

Read more about the Distributed CI setup with Nx Cloud.

1version: 2.1
2orbs:
3  nx: nrwl/nx@1.5.1
4jobs:
5  agent:
6    docker:
7      - image: cimg/node:lts-browsers
8    parameters:
9      ordinal:
10        type: integer
11    steps:
12      - checkout
13      - run: npm ci
14      - run:
15          command: npx nx-cloud start-agent
16          no_output_timeout: 60m
17  main:
18    docker:
19      - image: cimg/node:lts-browsers
20    steps:
21      - checkout
22      - run: npm ci
23      - nx/set-shas
24      - run: npx nx-cloud start-ci-run --stop-agents-after="build"
25
26      - run: npx nx-cloud record -- npx nx workspace-lint
27      - run: npx nx-cloud record -- npx nx format:check
28      - run: npx nx affected --base=$NX_BASE --head=$NX_HEAD --target=lint --parallel=3
29      - run: npx nx affected --base=$NX_BASE --head=$NX_HEAD --target=test --parallel=3 --ci --code-coverage
30      - run: npx nx affected --base=$NX_BASE --head=$NX_HEAD --target=build --parallel=3
31workflows:
32  build:
33    jobs:
34      - agent:
35          matrix:
36            parameters:
37              ordinal: [1, 2, 3]
38      - main
39

You can also use our ci-workflow generator to generate the configuration file.