Configuring CI Using Jenkins and Nx

Nx is a smart and extensible build framework, and it works really well with monorepos. Monorepos provide a lot of advantages:

  • Everything at that current commit works together. Changes can be verified across all affected parts of the organization.
  • Easy to split code into composable modules
  • Easier dependency management
  • One toolchain setup
  • Code editors and IDEs are "workspace" aware
  • Consistent developer experience
  • And more ...

But they come with their own technical challenges. The more code you add into your repository, the slower the CI gets. Adding Nx to your CI pipeline makes this more efficient.

Setting up Jenkins

Below is an example of a Jenkins setup for an Nx workspace only building and testing what is affected.

Unlike GitHub Actions and CircleCI, you don't have the metadata to help you track the last successful run on main. In the example below, the base is set to HEAD~1, but a more robust solution would be to tag a SHA in the main job once it succeeds, and then use this tag as a base.

We also have to set NX_BRANCH explicitly.

1pipeline {
2agent none
3environment {
5NX_BRANCH = env.BRANCH_NAME.replace('PR-', '')
7stages {
8stage('Pipelien') {
9parallel {
10stage('Agent') {
11matrix {
12agent any
13axes {
14axis {
15name 'Number'
16values '1', '2', '3'
19steps {
20sh "npm install"
21sh "npx nx-cloud start"
25stage('Main') {
26when {
27branch 'main'
29agent any
30steps {
31sh "npm install"
32sh "npx nx-cloud start-ci-run"
33sh "npx nx affected --base=HEAD~1 --target=build --parallel --max-parallel=3"
34sh "npx nx affected --base=HEAD~1 --target=test --parallel --max-parallel=2"
35sh "npx nx-cloud stop-all-agents"
38stage('PR') {
39when {
40not { branch 'main' }
42agent any
43steps {
44sh "npm install"
45sh "npx nx-cloud start-ci-run"
46sh "npx nx affected --target=build --parallel --max-parallel=3"
47sh "npx nx affected --target=test --parallel --max-parallel=2"
48sh "npx nx-cloud stop-all-agents"

The pr and main jobs implement the CI workflow.

Distributed CI with Nx Cloud

A computation cache is created on your local machine to make the developer experience faster. This allows you to not waste time re-building, re-testing, re-linting, or any number of other actions you might take on code that hasn’t changed. Because the cache is stored locally, you are the only member of your team that can take advantage of these instant commands. You can manage and share this cache manually.

Nx Cloud allows this cache to be shared across your entire organization, meaning that any cacheable operation completed on your workspace only needs to be run once.

Learn more about configuring your CI environment using Nx Cloud with Distributed Caching and Distributed Task Execution in the Nx Cloud docs.