Getting your npm package version from bash

This question came up for me and since I spent more than 5 minutes looking it up and didn’t find this answer anywhere else I wanted to document it.

The way to do it through npm is to add a script to your package.json file like so:

{
  "name": "example",
  "version": "1.0.0",
  "scripts": {
    "version": "echo $npm_package_version"
  }
}

Then you can do this to get the version from bash:

$ CURRENT_VERSION=$(npm run version --silent)

If you want to do automation as npm scripts, you can just access the $npm_package_version variable directly in your scripts.

The longer explanation here is that when you run an npm script it will automatically pull out all of the values from the package.json and put them into environment variables with the pattern npm_package_*. This means you can expose those variables as scripts if you want to use them externally.

The alternate version that I saw elsewhere was to just grab it using node like so:

$ CURRENT_VERSION=$(node -p "require('./package.json').version")

Author: justinmchase

I'm a Software Developer from Minnesota.

Drop a brain bomb

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s