Reputation: 2224
I should only need to do:
import dotenv from "dotenv";
dotenv.config();
in the index.js file. But my .env
variables only work when I explicitly import and configure dotenv in each file that uses .env variables.
This is my tsconfig.json
:
{
"compilerOptions": {
"rootDirs": ["src"],
"baseUrl": "./src",
"outDir": "dist",
"lib": ["es2020"],
"target": "es2020",
"module": "esnext",
"moduleResolution": "node",
"allowJs": true,
"esModuleInterop": true,
"types": ["node"]
},
}
Not sure why, any ideas?
Upvotes: 5
Views: 4138
Reputation: 21
import 'dotenv/config';
This would work. But also it needs to be called top of the other imports. Documentation
Upvotes: 2
Reputation: 36
import * as dotenv from 'dotenv'
dotenv.config()
would do the work. for more information visit https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
Upvotes: 0
Reputation: 7767
Imports are hoisted, so your dotenv.config
isn't being called until after the rest of your imports. To make this work with one import/config call, you can put that in a separate file and import that instead:
// env.ts
import dotenv from 'dotenv'
dotenv.config()
// index.ts
import './env'
// followed by all your other imports
And in the future, please post your code, not screenshots of your code. It's faster and easier to just copy-paste!
Upvotes: 12