Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

express - Toggle between multiple .env files like .env.development with node.js

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).

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...

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}` })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...