简体   繁体   中英

Load Local Environmental Variables For Use In NPM Scripts

I have an NPM script that looks like this:

"start": "server start --host $DEV_HOST"

There are lots of other scripts that also reference the $DEV_HOST env.

Currently $DEV_HOST is exported in my ~/.bashrc , but I would like to find a way of defining it locally to the project, for example in a .env file.

I wondered if npm offered a preall hook which would allow a simple bash file to be called which could load in the local envs, but no such hook exists.

It also appears that NPM doesn't offer any load mechanism for local envs out of the box.

The only solutions I can currently think of are:

  1. Move all the scripts that need the local env to their own bash files and load in the .env file in each of these.

  2. Call a separate script before each script that needs the local env that loads in the envs from the .env file.

Both of these seem unnecessarily cumbersome and don't scale well.

Is there any way of loading envs defined in a project-local file so that they are available for use in NPM scripts?

Note: I'm not asking how to load envs into an app. I'm asking how to make envs available to npm scripts. The two things are completely different. Dot-env adds envs to the current process. Even if you created a node script that used dot-env to load some envs, those envs wouldn't be available via $ variables as they are not loaded into the environment. They would only be available within the same process via process.env .

You can simply echo an environment variable in your NPM script.

For example, run the following on your command line in your project root:

export SOME_ENV=blalala

then in your package.json you can use it like so:

"scrips:" {
  "print-env": "echo $SOME_ENV"
}

this outputs blalala to the console.

If you want to define environment variables in a .env to be available in your scripts use something like this: https://www.npmjs.com/package/better-npm-run

npm i better-npm-run

create your .env file then use the variables exactly as shown above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM