简体   繁体   中英

How to define different vars for different environment in node.js?

I start to use dotenv for defining my env vars. I can easily specify my common vars for dev and prod environment in one .env file. But how to specify different vars for development and production environment.

For example I want to use DB_NAME = dev_db for development and DB_NAME = prod_db for production. How can I achieve this with dotenv ?

I'm working with node.js. Thank you in advance!

The .env file is supposed to be different on different environments, and hence should not be committed to your source control repo (for Git this would mean .gitignore).

For example, you'd have a config.env on production with this:

DB_NAME=prod_db

And on development, like this:

DB_NAME=dev_db

On both environments, the files would be named config.env and would reside in the same location so that the code will read the correct file.

In my project, the committed file is called config.env.sample that contains all the necessary values so that developers know what they need to add to the config.env in their environment:

# config.env.sample
# Sample configuration file for Project XYZ

# Name of the database
DB_NAME=dev_db

Here is more information from the FAQ :

Should I commit my .env file?

No. We strongly recommend against committing your .env file to version control. It should only include environment-specific values such as database passwords or API keys. Your production database should have a different password than your development database.

Should I have multiple .env files?

No. We strongly recommend against having a "main" .env file and an "environment" .env file like .env.test. Your config should vary between deploys, and you should not be sharing values between environments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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