Warm tip: This article is reproduced from serverfault.com, please click

Environment variables not working with Typescript and NodeJS

发布于 2020-11-29 12:22:01

My process.env file has this:

DB_NAME = hello

When I run my index.ts file which has this:

import { MikroORM } from '@mikro-orm/core';
import { __prod__ } from './constants';
import { Post } from './entities/Post';
import microConfig from './mikro-orm.config';

console.log(`console log is : ${process.env.DB_NAME}`);
const main = async () => {
  const orm = await MikroORM.init(microConfig);

  const post = orm.em.create(Post, { title: 'my first post' }); 
  orm.em.persistAndFlush(post); 
};

main();

It gives the value of process.env.DB_NAME as undefined.

My package.json is set up as follows:

{
  "name": "shreddit-backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node dist/index.js",
    "dev": "nodemon dist/index.js",
    "watch": "tsc -w",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^14.14.10",
    "nodemon": "^2.0.6",
    "ts-node": "^9.0.0",
    "typescript": "^4.1.2"
  },
  "dependencies": {
    "@mikro-orm/cli": "^4.3.2",
    "@mikro-orm/core": "^4.3.2",
    "@mikro-orm/migrations": "^4.3.2",
    "@mikro-orm/postgresql": "^4.3.2",
    "pg": "^8.5.1"
  },
  "mikro-orm": {
    "useTsNode": true,
    "configPaths": [
      "./src/mikro-orm.config.ts",
      "./dist/mikro-orm.config.js"
    ]
  }
}

I even tried using dotenv but that too wasn't able to fix the problem. Am I missing something? Thanks a lot.

Questioner
Arsh Sharma
Viewed
0
Tibebes. M 2020-11-29 20:39:15

Doesn't the process.env file automatically get loaded?

No, You're going to have to use dotenv.config as the following (at the very start of the script).

require('dotenv').config({ path: './process.env' })

// the rest of your code

Note that you can simply call .config without any arguments should your file be named just '.env' (which the de facto standard name for such purposes) - and not 'process.env'