使用node.js在.env.development等多个.env文件之间切换 [英] Toggle between multiple .env files like .env.development with node.js

查看:208
本文介绍了使用node.js在.env.development等多个.env文件之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为每种模式(开发,生产等)使用单独的.env文件.在处理vue.js项目时,我可以使用 .env.development .env.production 之类的文件为同一env密钥获取不同的值.(例如:在开发环境中,在.env.development中:FOO = BAR,在.env.production中:FOO = BAZ.在生产模式中,env.FOO为BAR,在生产中为BAZ).

I want to use separate .env files for each mode (development, production, etc...). When working on my vue.js projects, I can use files like .env.development or .env.production to get different values for the same env key. (example: in .env.development: FOO=BAR and in .env.production: FOO=BAZ, in development mode process.env.FOO would be BAR, in production i'd be BAZ).

我正在使用Express服务器,并希望使用这些相同类型的.env文件来存储端口,db uri,用户,pwd ...

I'm working on an Express server and want to use these same kinds of .env files to store the port, db uri, user, pwd...

我知道我可以像这样编辑package.json中的脚本:

I know I can edit the scripts in package.json like this:

"scripts": {
    "start": "NODE_ENV=development PORT=80 node ./bin/www",
    "start-prod": "NODE_ENV=production PORT=81 node ./bin/www"
}

但是使用多个变量时会变得混乱.

but this gets messy when using multiple variables.

我尝试使用 dotenv ,但看来您只能使用.env文件.不是.env.development和.env.production.

I've tried using dotenv but it seems like you can only use the .env file. Not .env.development and .env.production.

我可以使用dotenv软件包还是需要另一个软件包?还是我根本不用任何包装就可以做到这一点?

Can I use the dotenv package or do I need another one? Or could I do this without any package at all?

推荐答案

您可以通过 path 选项,如下所示:

You can specify which .env file path to use via the path option with something like this:

require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })

这篇关于使用node.js在.env.development等多个.env文件之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆