0

On my root directory of my project, I have a package.json. While doing the CI build, I am trying to capture the version properties from the file. Since I am running on a node container, the following command is possible.

node -p -e require('./package.json').version

I included the above in scripts property of package.json

  "scripts": {
     "version": "node -p -e require('./package.json').version"
   },

I am capturing it in a variable using

export VERSION=$(npm run version)

which seems to capture a lot more than the result of the npm command. Build environment is a Nodejs10 container built on rhel7.

jq is not available and something without it may be better

Any suggestions?

2
  • 1) Change your npm script to: "version": "node -p \"require('./package.json').version\"" - The -e option is not necessary, also the js to be evaluated must be passed as a string. Note it's been encased in JSON escaped double quotes, i.e. \". 2) Also capture and export it using the following code instead; export VERSION=$(npm run version -s) - note the additional -s option (which is the shorthand for --silent) - this ensures you capture only the version (e.g. 1.0.0) and not the additional npm log info.
    – RobC
    Commented Aug 11, 2020 at 14:30
  • 1
    Thanks RobC. Exactly what I was looking for. You may post it as a answer and I will accept it Commented Aug 12, 2020 at 14:34

2 Answers 2

2
  1. Change your npm script to:

    "scripts": {
      "version": "node -p \"require('./package.json').version\""
    }
    

    The -e option is not necessary, also the JavaScript to be evaluated must be passed as a string. Note it's been encased in JSON escaped double quotes, i.e. \".

  2. Also capture and export it using the following code instead:

    export VERSION=$(npm run version -s)
    

    Note the additional -s option (which is the shorthand for --silent) - this ensures you capture only the version (e.g. 1.0.0) and not the additional npm log info.

0

packege.json can reference itself using the following pattern

$npm_package_PROP[_SUB_PROP][_SUB_SUB_PROP]

  "version": "1.0.0",
  "scripts": {
    ...
    "version": "echo $npm_package_version"
  },
npm run version # output: 1.0.0
1
  • What is the NPM version you are using?
    – Daniel
    Commented Aug 12, 2020 at 14:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.