autoenv v2.0.1
AutoENV
automatically load dotenv files based on NODE_ENV
autoenv uses dotenv to automatically load environment variables from a compatible .env file into process.env.
Install
npm install autoenvConfig
Create a default .env file in the root directory of your project.
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3Create additional .env.xyz files matching as many environment variants you want:
my_project/
āāā .env
āāā .env.development
āāā .env.staging
āāā .env.productionThe default .env will always be loaded, if a matching .env.${NODE_ENV} file is present, it will be loaded and overrides the values in .env
Usage
As early as possible in your application, require and configure dotenv.
require('autoenv')When starting your application, ensure NODE_ENV is set to the environment name you wish to load.
NODE_ENV=staging node index.jsexport NODE_ENV=staging
node index.jsPreload
You can use the --require (-r) command line option to preload autoenv. By doing this, you do not need to require in your application code.
node -r autoenv index.jsThat's it.
process.env now has the keys and values you defined in your .env file.
const db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})Author: Ahmad Nassri ⢠Twitter: @AhmadNassri