我将按照文档here中所述在nestjs中配置环境变量:
在我的服务构造函数中,我得到了环境文件路径
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中获取环境变量路径
答案 0 :(得分:1)
我也遇到过同样的问题。可以轻松地通过手动将dotenv导入文件main.ts
中来修复它,就像下面的示例一样(请确保已安装dotenv
):
import { NestFactory } from '@nestjs/core';
import { config } from 'dotenv';
config();
// all rest of your code
希望这会有所帮助!