How to get package.json version


package.json vars

In package scripts, you can reference the environment variable $npm_package_version:

{
  "scripts": {
    "get-version": "echo $npm_package_version"
  },
  "version": "1.2.3"
}

Run the script to get the version:

$ npm run get-version

> @1.2.3 get-version path/to/package
> echo $npm_package_version

1.2.3

jq

jq is a powerful program for filtering JSON (if you have it installed):

{
  "scripts": {
    "get-version": "jq -r '.version' package.json"
  },
  "version": "1.2.3"
}

The option -r outputs the raw string (1.2.3 instead of "1.2.3").

Run the script to get the version:

$ npm run get-version

> @1.2.3 get-version path/to/package
> jq -r '.version' package.json

1.2.3

node script

With Node.js installed, you can eval a script with the option -e:

{
  "scripts": {
    "get-version": "node -e \"console.log(require('./package.json').version)\""
  },
  "version": "1.2.3"
}

Run the script to get the version:

$ npm run get-version

> @1.2.3 get-version path/to/package
> node -e "console.log(require('./package.json').version)"

1.2.3

To shorten the script, you can pass the option -p to print the evaluation:

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

awk

And you can always process text with awk:

{
  "scripts": {
    "get-version": "awk -F'\"' '/\"version\": \".+\"/{ print $4; exit; }' package.json"
  },
  "version": "1.2.3"
}

Here we’re matching package.json against the regex pattern /"version": ".+"/ and printing the 4th field of the first result.

Run the script to get the version:

$ npm run get-version

> @1.2.3 get-version path/to/package
> awk -F'"' '/"version": ".+"/{ print $4; exit; }' package.json

1.2.3

What approach do you use to retrieve the package version? Let me know in the comments below.