简体   繁体   English

环境变量不适用于 Typescript 和 NodeJS

[英]Environment variables not working with Typescript and NodeJS

My process.env file has this:我的 process.env 文件有这个:

DB_NAME = hello

When I run my index.ts file which has this:当我运行包含以下内容的index.ts文件时:

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.它给出了未定义的process.env.DB_NAME值。

My package.json is set up as follows:我的 package.json 设置如下:

{
  "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.我什至尝试使用dotenv但这也无法解决问题。 Am I missing something?我错过了什么吗? Thanks a lot.非常感谢。

Doesn't the process.env file automatically get loaded? process.env 文件不会自动加载吗?

No, You're going to have to use dotenv.config as the following (at the very start of the script).不,您将不得不使用dotenv.config如下(在脚本的开头)。

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'请注意,如果您的文件仅命名为'.env' (用于此类目的的事实上的标准名称)而不是'process.env' ,则您可以在没有任何 arguments 的情况下简单地调用.config

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM