简体   繁体   English

加载本地环境变量以用于NPM脚本

[英]Load Local Environmental Variables For Use In NPM Scripts

I have an NPM script that looks like this: 我有一个NPM脚本,如下所示:

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

There are lots of other scripts that also reference the $DEV_HOST env. 还有许多其他脚本也引用$DEV_HOST

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. 当前$DEV_HOST已导出到我的~/.bashrc ,但是我想找到一种在项目中本地定义它的方法,例如在.env文件中。

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. 我想知道npm是否提供了一个preall钩子,该钩子将允许调用一个可以在本地envs中加载的简单bash文件,但是不存在这样的钩子。

It also appears that NPM doesn't offer any load mechanism for local envs out of the box. NPM似乎也没有为本地环境提供任何加载机制。

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. 将所有需要本地env的脚本移动到它们自己的bash文件中,并在每个脚本中加载.env文件。

  2. Call a separate script before each script that needs the local env that loads in the envs from the .env file. 在需要从.env文件加载到envs中的需要本地env的每个脚本之前,调用一个单独的脚本。

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? 有什么方法可以加载在项目本地文件中定义的环境,以便可以在NPM脚本中使用它们?

Note: I'm not asking how to load envs into an app. 注意: 我不是在问如何将env加载到应用程序中。 I'm asking how to make envs available to npm scripts. 我在问如何使nv脚本可以使用env。 The two things are completely different. 这两件事完全不同。 Dot-env adds envs to the current process. Dot-env将envs添加到当前进程。 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. 即使您创建了使用dot-env加载某些env的节点脚本,这些env也不会通过$变量提供,因为它们没有加载到环境中。 They would only be available within the same process via process.env . 它们只能通过process.env在同一进程中使用。

You can simply echo an environment variable in your NPM script. 您只需在NPM脚本中回显一个环境变量即可。

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: 然后可以在package.json像这样使用它:

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

this outputs blalala to the console. blalala输出到控制台。

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 如果要在脚本中可用的.env定义环境变量,请使用类似以下内容的内容: https : .env

npm i better-npm-run

create your .env file then use the variables exactly as shown above 创建您的.env文件,然后完全如上所示使用变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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