I am using an .env file to hold environment variables for the server. This works if I run the server with foreman start. But it doesn\'t work with nodemon.
I would
npm i dotenv
.env
file and your variables insideAdd the script to execute
"dev": "nodemon -r dotenv/config ./app/index.js " or
"start": "node -r dotenv/config ./app/index.js "
Run the app using npm run dev
or npm run start
With recent versions of Node (since io.js 1.6), you can pass it the -r
flag to require a module on start. This lets you directly load .env
by using nodemon's --exec
:
nodemon --exec 'node -r dotenv/config'
This requires the npm package dotenv to be installed.
I have a production Procfile with:
web: node web.js
So I have created a Procfile_dev file with:
web: nodemon web.js
And when I am at development environment I run:
$ foreman start -f Procfile_dev
It works like a charm and doesn't affect production.
You can get nodemon to directly use the .env with the following command
$: env $(cat .env) nodemon app.js
Be aware that you'll have to restart it if you make changes to .env and it won't like it if there are any spaces in your .env file.
This works pretty well for me so far,
nodemon -w . -w .env index.js
How it works:
"-w ." tells nodemon to watch the files in the current directory
"-w .env" tells nodemon to watch the .env file
"index.js" is just the file to run when changes occur (could be anything)