I know we can declare env variables to be used inside the script run by npm run
command like so:
TEMP_VARIABLE=value node app.js
But if I need to use the declared variable across multiple npm run
scripts, then it will lead to duplicate the effort to specifying the value of variable each time, like in following code example:
"start": "SRC_DIR=src node src/app.js",
"lint": "SRC_DIR=src jshint src/*.js",
"coverage": "SRC_DIR=src istanbul cover --dir outputDir -i src/*.js"
Is there a way so that we can use npm run-script
to export a env variable to allow something like below:
"scripts": {
"set-env": "export SRC_DIR=src", # should export the env var to be used later
"start": "node ${SRC_DIR}/app.js", # use the env var set earlier.
"lint": "jshint ${SRC_DIR}/*.js" # use the same env var again
"coverage": "istanbul cover -d ./lcov -i ${SRC_DIR}/*.js" # use again
}
Then we can just do:
npm run set-env
npm run lint
npm run start
To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").
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 .
ANSWER: You have a few options: better-npm-run,which can define an env for each command separately. Instead of a poststart script, you can concatenate commands for npm like so: "start": "NODE_ENV=${NODE_ENV:=production} node start-app.
You can use environment values to inject in your package. json like this: Any environment variables that start with npm_config_ will be interpreted as a configuration parameter. For example, putting npm_config_foo=bar in your environment will set the foo configuration parameter to bar.
if you use yarn as your package manager, try this command it is easy to find out how to make it happen
yarn run env
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With