Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export env variable from npm script?

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
like image 603
codneto Avatar asked Nov 26 '15 22:11

codneto


People also ask

How do I export a .env variable?

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 ").

How do I get environment variables in package JSON?

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 .

How do I pass an environment variable to a npm script?

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.

Can you use env variables in package JSON?

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.


1 Answers

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

like image 100
briefy Avatar answered Oct 07 '22 12:10

briefy