In my case I'm using TypeScript and the .env
file is used for development only. I wanted my code to be decoupled from the .env
file and I didn't want to import 'dotenv/config'
anywhere in my code. This is my solution:
My nodemon config:
{
"watch": [
"src",
".env"
],
"ext": ".ts",
"exec": "ts-node -r dotenv/config ./src/index.ts"
}
My NPM script:
"start:dev": "nodemon"
In this solution ts-node
requires dotenv, which sets up the environment variables before the main app starts. This means that nowhere in my code do I need a import 'dotenv/config'
. dotenv
can become a dev dependency, and this also prevents dotenv to be loaded at all once the code is deployed.