Configuring CI Using Jenkins and Nx

Below is an example of an Jenkins setup, building and testing only what is affected.

1pipeline { 2 agent none 3 environment { 4 NX_BRANCH = env.BRANCH_NAME.replace('PR-', '') 5 } 6 stages { 7 stage('Pipeline') { 8 parallel { 9 stage('Main') { 10 when { 11 branch 'main' 12 } 13 agent any 14 steps { 15 sh "npx nx-cloud start-ci-run --distribute-on='5 linux-medium-js' --stop-agents-after='build'" // this line enables distribution 16 sh "npm ci" 17 sh "npx nx-cloud record -- nx format:check" 18 sh "npx nx affected --base=HEAD~1 -t lint test build --parallel=3" 19 } 20 } 21 stage('PR') { 22 when { 23 not { branch 'main' } 24 } 25 agent any 26 steps { 27 sh "npx nx-cloud start-ci-run --distribute-on='5 linux-medium-js' --stop-agents-after='build'" // this line enables distribution 28 sh "npm ci" 29 sh "npx nx-cloud record -- nx format:check" 30 sh "npx nx affected --base origin/${env.CHANGE_TARGET} -t lint test build --parallel=3" 31 } 32 } 33 } 34 } 35 } 36} 37

Get the Commit of the Last Successful Build

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 (for push) or branching point (for pull requests), but a more robust solution would be to tag an SHA in the main job once it succeeds and then use this tag as a base. See the nx-tag-successful-ci-run and nx-set-shas (version 1 implements tagging mechanism) repositories for more information.

We also have to set NX_BRANCH explicitly.