有两个问题使ConfigService 不太有用。
第一
当任何环境中都没有.env文件时,readFileSync in
dotenv.parse(fs.readFileSync(filePath))
会失败:
[Nest] 63403 [ExceptionHandler] path must be a string or Buffer
TypeError: path must be a string or Buffer
at Object.fs.openSync (fs.js:646:18)
at Object.fs.readFileSync (fs.js:551:33)
at new ConfigService (../config/config.service.ts:8:38)
即使例如process.env.API_KEY 可用
this.configService.get('API_KEY')
不会返回任何东西。所以ConfigService 强制你使用prod.env 文件,这是dotenv 反对的:
没有。我们强烈建议不要使用“主” .env 文件和
“环境” .env 文件,如 .env.test。您的配置应该有所不同
在部署之间,您不应该在之间共享值
环境。
https://github.com/motdotla/dotenv#should-i-have-multiple-env-files
第二
您必须导入配置模块并注入服务才能使用它。当你使用这样的环境变量时
imports: [
MongooseModule.forRoot(process.env.MONGO_URI, { useNewUrlParser: true }),
ConfigModule,
],
配置服务没用。
在此处阅读有关环境中配置的更多信息:https://12factor.net/config