简体   繁体   English

没有.env文件时,如何使用dotEnv?

[英]How do I use dotEnv when there is no .env file?

I have a project that locally has a .env file. 我有一个本地有.env文件的项目。 When I set up the environment variables on my local machine I use: 在本地计算机上设置环境变量时,我使用:

import dotEnv from "dotenv";
dotEnv.config();

It find the .env and loads up all the variables. 它找到.env并加载所有变量。 When I push the project to Heroku, I don't push up the .env file. 当我将项目推送到Heroku时,我不会推送.env文件。 I expected dotEnv to understand that, but I get this error: 我希望dotEnv能够理解这一点,但是却出现此错误:

{ Error: ENOENT: no such file or directory, open '.env'

How do I get around that I am not pushing up a .env file? 如何避免我没有推送.env文件? What is the proper way to use .dotEnv ? 使用.dotEnv的正确方法是什么?

I'm a contributor to the dotenv module. 我是dotenv模块的贡献者。 You can safely ignore this error. 您可以放心地忽略此错误。 It is returned for your convenience in case something isn't working as expected. 为方便起见,将其返回,以防万一某些功能无法正常工作。

I don't much like the solution proposed here: https://github.com/motdotla/dotenv/issues/126 It amounts to conditionally requiring /dotenv depending on an environment variable being set. 我不太喜欢这里提出的解决方案: https : //github.com/motdotla/dotenv/issues/126这等于根据设置的环境变量有条件地要求/ dotenv。 This seems brittle and like extra work to me. 这似乎很脆弱,并且对我来说像是额外的工作。

The neatest solution for this I've found doesn't pollute my production code with any references to dotenv at all. 我发现的最整洁的解决方案完全不会污染任何dotenv的引用。 Just include dotenv in your dev dependencies and run your app locally using the node require switch: 只需在您的开发依赖项中包含dotenv,然后使用节点require开关在本地运行您的应用即可:

$ node -r dotenv/config ./lib/index.js

This is the same way you might load babel-register. 这与加载babel-register的方式相同。

Now your code doesn't care about where the env variables come from. 现在,您的代码不再关心env变量的来源。 Works with nodemon, etc. too. 也可以与nodemon等一起使用。 You can even specify an alternate env file: 您甚至可以指定一个备用环境文件:

$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars

It's all on the npm page for the package. 全部在软件包的npm页面上。

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

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