Using npm configuration environment variables in package.json

Published: | Updated: | by Julian Knight Reading time ~1 min.
📖 Kb | 📎 Development | 🔖 node.js, nodejs, npm, json

npm automatically makes parts of your package.json file available as environment variables. This can be useful when using npm as a run script service.

npm exposes all of the entries in package.json as environment variables so that any script specified in the scripts section can make use of them.

In the example below we can see both the advantage and the weakness of the approach.

The advantage is that we can pass things like the module version number direct to another command.

The weakness is that the consumption of environment variables is different depending on the operating system in use.

Every property in package.json is exposed this way, simply prefix with npm_package_ and replace subscripts (e.g. scripts.patch) with an underscore (e.g. npm_package_scripts_patch).

Example package.json 🔗︎

We can use this for reference

  "name": "Config Example",
  "version": "1.2.3",
  "description": "Using config variables in package.json",
  "author": "Max Headroom",
  "scripts": {
    "patch": "npm version patch -m \"Patch version bump to %s\" ",
    "minor": "npm version minor -m \"Minor version bump to %s\" ",
    "major": "npm version major -m \"Major version bump to %s\"",

    "postinstall": "node ./postinstall.js",

    "win-tag": "git tag -a v%npm_package_version% -m \"Release v%npm_package_version%\"; git push origin --tags",
    "tag": "git tag -a v$npm_package_version -m \"Release v$npm_package_version\" && git push origin --tags"
  "devDependencies": {
    "eslint": "^1.10.3",

References 🔗︎

comments powered by Disqus