The simplest cross-platform approach is to use cross-env.
Recommended: cross-env
Install it:
npm install --save-dev cross-env
Then in package.json:
{
"scripts": {
"start": "cross-env NODE_ENV=production node app.js"
}
}
Now this works the same in Windows, macOS, and Linux:
npm start
You can also pass multiple variables:
{
"scripts": {
"build": "cross-env NODE_ENV=production API_URL=https://example.com node build.js"
}
}
Without cross-env
On macOS/Linux:
NODE_ENV=production npm start
On Windows CMD:
set NODE_ENV=production && npm start
On PowerShell:
$env:NODE_ENV="production"; npm start
Those syntaxes differ, which is why cross-env is usually preferable for npm scripts.
One important distinction: if you mean passing an environment variable into an npm script from the command line, cross-env isn't necessary. You can do:
# macOS/Linux
FOO=bar npm run myscript
but cross-platform portability again favors cross-env.