在 nest.js 中未定义 process.env.variable [英] process.env.varible undefined in nest.js
问题描述
我正在使用 nest.js 并且我想导入 auth.parameters.ts 文件中定义的对象.文件定义如下.除非在类中声明以下变量,否则环境变量似乎不可见.
export const obj = {somevar : process.env.CUSTOM_VAR,};
在我的其他课程中,我想使用 import {SecurityParameters } from '../auth/auth.parameters' 导入文件
并使用 console.log(SecurityParameters.somevar) 访问该变量.
我可以使用 process.env.CUSTOM_VAR 或
直接访问变量如果我在其他文件中使用 somevar : process.env.CUSTOM_VAR,我会得到未定义.
当您使用 Nest 的 ConfigModule
时,除非您正在创建 自定义配置文件 你不应该对 process.env
做任何事情.相反,您应该在需要环境变量的地方注入 Nest 的 ConfigService
并使用 this.configService.get('CUSTOM_VARIABLE')
(或您需要的任何值).要开始使用此功能,您需要导入配置模块
import { Module } from '@nestjs/common';从'@nestjs/config' 导入 { ConfigModule };@模块({进口:[ConfigModule.forRoot()],})导出类 AppModule {}
您可以将 { isGlobal: true }
传递给 forRoot()
调用,使 ConfigService
可在您的应用程序中的任何位置注入.>
如果您想要一种不同的方法来代替使用 process.env
对象,您可以将其添加为 main 的前两行.ts
import { config } from 'dotenv';配置();
Nest 在 ConfigService
的幕后调用它(或类似的东西),但这并不能立即使用.
I am using nest.js and I want to import object defined in auth.parameters.ts file. File is defined as below. It appears environmental variable is not visible unless below variable is declared in class.
export const obj = {
somevar : process.env.CUSTOM_VAR,
};
In my other classes I would like to import the file with import {SecurityParameters } from '../auth/auth.parameters'
and access the variable with console.log(SecurityParameters.somevar).
I can access the variable directly using process.env.CUSTOM_VAR or
I get undefined if I use somevar : process.env.CUSTOM_VAR in other file.
As you're using Nest's ConfigModule
, then unless you're creating a custom config file you shouldn't be doing anything with process.env
. Instead, you should be injecting Nest's ConfigService
where you need the environment variables and using this.configService.get('CUSTOM_VARIABLE')
(or whatever value you need). To get started with this, you need to import the config module
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule.forRoot()],
})
export class AppModule {}
You can pass { isGlobal: true }
to the forRoot()
call to make the ConfigService
injectable anywhere in your application.
If you want a different approach where you can use the process.env
object instead, you can add this as the first two lines of your main.ts
import { config } from 'dotenv';
config();
Nest calls this (or something similar) under the hood in the ConfigService
, but that doesn't make it immediately available.
这篇关于在 nest.js 中未定义 process.env.variable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!