【问题标题】:nestJs handle env variablesnestJs 处理环境变量
【发布时间】:2019-09-29 04:47:56
【问题描述】:

如文档here 中所述,我将在nestjs 中配置enivrement 变量:

在我的服务构造函数中,我得到了 env 文件路径

import * as dotenv from 'dotenv';
import * as fs from 'fs';

export class ConfigService {
  private readonly envConfig: { [key: string]: string };

  constructor(filePath: string) {
    this.envConfig = dotenv.parse(fs.readFileSync(filePath))
    console.log(this.envConfig)
  }

  get(key: string): string {
    return this.envConfig[key];
  }
}

然后在配置模块中设置配置服务

  providers: [
    {
      provide: ConfigService,
      useValue: new ConfigService(`${process.env.NODE_ENV}.env`),
    },
  ],
  exports: [ConfigService],
})

当前行为

实际上我得到了未定义的 process.env.NODE_ENV 值

预期行为

在 process.env.NODE_ENV 中获取环境变量路径

【问题讨论】:

标签: javascript node.js nestjs dotenv


【解决方案1】:

我也遇到过同样的问题。通过在文件main.ts 中手动导入dotenv 来轻松修复它,就像在下面的示例中一样(请确保您已经安装了dotenv):

import { NestFactory } from '@nestjs/core';
import { config } from 'dotenv';
config();
// all rest of your code

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2020-03-12
    • 2020-08-09
    • 2022-01-07
    • 2021-08-01
    • 2022-01-10
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    相关资源
    最近更新 更多