How to export env variable from npm script?
Asked Answered
G

2

11

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
Grantgranta answered 26/11, 2015 at 22:23 Comment(2)
Why not use configobject: docs.npmjs.com/files/package.json#config?Islean
I want to do the same thing, except that I don't want to set a static value, I want to update the value of the $PATH environment variable. In that case, config won't work.Observe
P
1

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

Pancho answered 5/11, 2018 at 11:37 Comment(0)
V
0

You can achieve that behavior by using a different package.json feature, npm-config.

Example

This following is an adaption of your code.

{
    "config": {
         "srcDir": "src"
    },
    "scripts": {
         "start": "node ${npm_package_config_srcDir}/app.js",
         "lint": "jshint ${npm_package_config_srcDir}/*.js",
         "coverage": "istanbul cover -d ./lcov -i ${npm_package_config_srcDir}/*.js"
    }
}

Official Documentation

Vanillic answered 27/5, 2016 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.