Environment variable with dotenv and TypeScript

user13111868 picture user13111868 · Jun 9, 2020 · Viewed 29.4k times · Source

I create this .env file:

TYPE=xxx
HOST=xxx,
PORT=xxx,
USERNAME=xxx,
PASSWORD=xxx,
DATABASE=xxx,

in my file I use in this way:

import * as dotenv from "dotenv";

dotenv.config();

export const typeOrmConfig: TypeOrmModuleOptions = {
    port: process.env.PORT
}

but i can use only my port variable from .env file and i cannot use rest of the variables, can someone tell me why i can't use rest of my vars?

Answer

ZaHuPro picture ZaHuPro · Jun 9, 2020

Actually you have define the path of the .env file

Try like this

import * as dotenv from "dotenv";
dotenv.config({ path: __dirname+'/.env' });

Try this also

require('dotenv').config({ path: __dirname+'/.env' });

Change the path of .env file as required

reference : https://www.npmjs.com/package/dotenv