Because I often find myself working with multiple environment variables, I find it useful to keep them in a separate .env
file (make sure to ignore this from your source control). Then (in Linux) prepend export $(cat .env | xargs) &&
in your script command before starting your app.
Example .env
file:
VAR_A=Hello World
VAR_B=format the .env file like this with new vars separated by a line break
Example index.js
:
console.log('Test', process.env.VAR_A, process.env.VAR_B);
Example package.json
:
{
...
"scripts": {
"start": "node index.js",
"env-linux": "export $(cat .env | xargs) && env",
"start-linux": "export $(cat .env | xargs) && npm start",
"env-windows": "(for /F \"tokens=*\" %i in (.env) do set %i)",
"start-windows": "(for /F \"tokens=*\" %i in (.env) do set %i) && npm start",
}
...
}
Unfortunately I can't seem to set the environment variables by calling a script from a script -- like "start-windows": "npm run env-windows && npm start"
-- so there is some redundancy in the scripts.
For a test you can see the env variables by running npm run env-linux
or npm run env-windows
, and test that they make it into your app by running npm run start-linux
or npm run start-windows
.