use*_*842 1 javascript node.js nestjs
我正在使用 Nest.js,我想导入 auth.parameters.ts 文件中定义的对象。文件定义如下。除非在类中声明以下变量,否则环境变量似乎不可见。
export const obj = {
somevar : process.env.CUSTOM_VAR,
};
Run Code Online (Sandbox Code Playgroud)
在我的其他课程中,我想使用 import {SecurityParameters } from '../auth/auth.parameters' 导入文件
并使用 console.log(SecurityParameters.somevar) 访问该变量。
我可以使用 process.env.CUSTOM_VAR 直接访问变量或
如果我在其他文件中使用 somevar : process.env.CUSTOM_VAR ,我会得到未定义。
当您使用 Nest 的ConfigModule时,除非您创建自定义配置文件,否则您不应该对process.env. 相反,您应该ConfigService在需要环境变量的地方注入 Nest 并使用this.configService.get('CUSTOM_VARIABLE')(或您需要的任何值)。首先,您需要导入配置模块
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule.forRoot()],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
您可以传递{ isGlobal: true }调用以在应用程序的任何位置forRoot()进行注入。ConfigService
如果您想要一种可以使用该process.env对象的不同方法,您可以将其添加为您的前两行main.ts
import { config } from 'dotenv';
config();
Run Code Online (Sandbox Code Playgroud)
Nest 在 的幕后调用此(或类似的内容)ConfigService,但这并不使其立即可用。
| 归档时间: |
|
| 查看次数: |
6413 次 |
| 最近记录: |