Reputation: 2469
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
Upvotes: 11
Views: 5700
Reputation: 21
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"]
Upvotes: 0
Reputation: 221
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
Upvotes: 1
Reputation: 4779
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
Upvotes: 0