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
2
  • Why not use configobject: docs.npmjs.com/files/package.json#config? Commented Nov 26, 2015 at 22:48
  • 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. Commented Dec 27, 2017 at 21:51

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Yes, this can be done easily if you're using docker.

Sample Dockerfile

# ================= #
# Development Stage
# ================= #
FROM node:18-alpine AS development

# Add bash shell
RUN apk add --no-cache bash
WORKDIR /usr/src/app
COPY . .

# Install nodemon
RUN npm i -g nodemon rimraf

# ======================================== #
ENV NODE_ENV=development 
# Adding the environment variable here will load the env-var for the container. 
# ======================================== #

# Install packages and build
RUN yarn config set globalFolder /usr/src/app/.yarn
RUN yarn install
RUN yarn build

# This command is to run the app
ENTRYPOINT ["/bin/bash", "-c", "yarn startdev"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.