Search code examples
jenkinsjenkins-pipeline

extract version from package.json with bash inside jenkins pipeline


Script in package.json:

"scripts": {
    "version": "echo $npm_package_version"
  },

One of the stage in Jenkins pipeline:

stage('Build'){
    sh 'npm install'
    def packageVersion = sh 'npm run version'
    echo $packageVersion
    sh 'VERSION=${packageVersion} npm run build'
}

I got version from npm script output, but following line

echo $packageVersion

return null

Is packageVersion value not correctly assigned?

Edited: when using Pipeline Utility Steps with following code

stage('Build'){
    def packageJSON = readJSON file: 'package.json'
    def packageJSONVersion = packageJSON.version
    echo packageJSONVersion
    sh 'VERSION=${packageJSONVersion}_${BUILD_NUMBER}_${BRANCH_NAME} npm run build'
        }

I get

[Pipeline] echo
1.1.0
[Pipeline] sh
[...] Running shell script + VERSION=_16_SOME_BRANCH npm run build

So I am able to extract version, but still cannot pass it when running script


Solution

  • After your edit using readJSON, you now get string interpolation wrong. Variables within single quotes are not replaced in Groovy, only within double quotes.

    sh 'VERSION=${packageJSONVersion}_${BUILD_NUMBER}_${BRANCH_NAME} npm run build'
    

    must be

    sh "VERSION=${packageJSONVersion}_${BUILD_NUMBER}_${BRANCH_NAME} npm run build"