Referencing Values in package.json as Variables

There is a simple way to reference values in npm-scripts inside package.json configuration file of your project. Just like every property is defined as a variable:

{
  "name": "classforus-socotra",
  "version": "1.0.7",
  "description": "",
  "private": true,
  "scripts": {
    "build": "NODE_ENV=production VERSION=$npm_package_version webpack -p"
  },
  ...
}

Now process.env.VERSION is going to be "1.0.7" inside npm "build" script.

Using$npm_package_KEY, it is possible to access particular key/property value. Even a value from a deeply nested object. Where KEY is a name of the property with nesting separated by _ (underscore) character:

  ...
  "repository": {
    "type": "git",
    "url": "git+https://github.com/classforus/classforus-socotra.git"
  },
  "scripts": {
    "repository": "echo \"Repository url: $npm_package_repository_url\""
  },
  ...
$ npm run repository

Repository url: git+https://github.com/classforus/classforus-socotra.git

Use Case

Reference any configuration value from a config object inside package.json. As well as, reference any paths from directories object:

  ...
  "directories": {
    "static": "./dist/static"
  },
  "config" : {
    "aws": {
      "bucket": "s3://umwerk-phoenixdesign",
      "region": "eu-central-1"
    },
    ...
  },
  "scripts": {
    "deploy:static": "aws s3 sync $npm_package_directories_static $npm_package_config_aws_bucket --region $npm_package_config_aws_region --delete --size-only"
  },
  ...

Now executing npm run deploy:static npm-script is going to pick values from referenced properties and sync changes to Amazon S3 bucket. Yes, it's that easy!

#nodejs #npm