Oamar Kanji
Oamar Kanji

Reputation: 2224

Environment variables only working when dotenv is imported and configured in each file (instead of just in index.ts)

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?

index.ts: enter image description here

connectToDatabase.ts enter image description here

.env enter image description here

enter image description here

Upvotes: 5

Views: 4138

Answers (3)

Bulut Yerli
Bulut Yerli

Reputation: 21

import 'dotenv/config';

This would work. But also it needs to be called top of the other imports. Documentation

Upvotes: 2

Yaz Rae
Yaz Rae

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

Zac Anger
Zac Anger

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

Related Questions