在多个 .env 文件之间切换,例如 .env.development 和 node.js [英] Toggle between multiple .env files like .env.development with node.js

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

问题描述

我想为每种模式(开发、生产等)使用单独的 .env 文件.在处理我的 vue.js 项目时,我可以使用像 .env.development.env.production 这样的文件来为同一个 env 键获取不同的值.(例如:在 .env.development:FOO=BAR 和在 .env.production:FOO=BAZ,在开发模式下 process.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}` })

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

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