简体   繁体   English

节点dotenv文件未加载测试环境

[英]node dotenv files not loading for test env

I have two dotenv files, one for development and another for test. 我有两个dotenv文件,一个用于开发,另一个用于测试。

const dotenv = require('dotenv');

if (process.env && process.env.NODE_ENV) {
  dotenv.config({path: '.env.' + process.env.NODE_ENV});
} else {
  dotenv.config({path: '.env.development'});
}

const http = require('http');
const app = require('../src/app');

const port = parseInt(process.env.PORT, 10) || 8000;
app.set('port', port);

const server = http.createServer(app);
server.listen(port);

Here are my questions: 这是我的问题:

When does server load dotenv files in my case? 什么时候服务器在我的情况下加载dotenv文件? If I run in test env, why do I get undefined for those process.env variables? 如果我在test运行,为什么我没有为那些process.env变量定义? It seems to me this file only runs once, when I change NODE_ENV, it does not change which file to load. 在我看来,这个文件只运行一次,当我更改NODE_ENV时,它不会更改要加载的文件。

So in short: 简而言之:

My development dotenv is working, but just having trouble when changing it to test dotenv 我的开发dotenv正在工作,但在更改它以test dotenv时遇到麻烦

Please take a look at the dotenv-flow package. 请查看dotenv-flow软件包。

This module extends dotenv adding the ability to have multiple .env* files like .env.development , .env.test , .env.production , etc., also allowing defined variables to be overwritten individually in the appropriate .env*.local file that is untracked by VCS. 此模块扩展了dotenv,增加了多个.env*文件的功能,如.env.development.env.test.env.production等,还允许在相应的.env*.local文件中单独覆盖定义的变量这是VCS未跟踪的。

Regarding to the recommendation against having multiple env files, dotenv-flow has a slightly different approach to manage .env* files under version control. 关于针对多个env文件的建议, dotenv-flow在版本控制下管理.env*文件的方法略有不同。 Please refer the Files under version control section to understand the motivation of this approach. 请参阅版本控制部分文件以了解此方法的动机。

Should I have multiple .env files? 我应该有多个.env文件吗?

No. We strongly recommend against having a "main" .env file and an "environment" .env file like .env.test. 不。我们强烈建议不要使用“主”.env文件和.env.test等“环境”.env文件。 Your config should vary between deploys, and you should not be sharing values between environments. 您的配置应该在部署之间有所不同,并且您不应该在环境之间共享值。

From dotenv documentation 来自dotenv文档

custom-env also solves this problem, it allows multiple configurations file for different environments. custom-env也解决了这个问题,它允许不同环境的多个配置文件。 npm install custom-env . npm install custom-env You can also specify which .env file to use on the go. 您还可以指定要在移动中使用的.env文件。 require('custom-env').env('test'); .

Full Docs here: https://www.npmjs.com/package/custom-env 完整文档: https//www.npmjs.com/package/custom-env

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

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