How to set environment variables from within package.json?

Set the environment variable in the script command:

...
"scripts": {
  "start": "node app.js",
  "test": "NODE_ENV=test mocha --reporter spec"
},
...

Then use process.env.NODE_ENV in your app.

Note: This is for Mac & Linux only. For Windows refer to the comments.


Just use NPM package cross-env. Super easy. Works on Windows, Linux, and all environments. Notice that you don't use && to move to the next task. You just set the env and then start the next task. Credit to @mikekidder for the suggestion in one of the comments here.

From documentation:

{
  "scripts": {
    "build": "cross-env NODE_ENV=production OTHERFLAG=myValue webpack --config build/webpack.config.js"
  }
}

Notice that if you want to set multiple global vars, you just state them in succession, followed by your command to be executed.

Ultimately, the command that is executed (using spawn) is:

webpack --config build/webpack.config.js

The NODE_ENV environment variable will be set by cross-env