> 文章列表 > 【NestJS】环境变量的配置与使用

【NestJS】环境变量的配置与使用

【NestJS】环境变量的配置与使用

@nestjs/config

NestJS 内置了 dotenv,并将其封装到 @nestjs/config 里面了

  1. npm i @nestjs/config
  2. 在 .env 文件中编写环境变量
TOKEN_SECRET = 'superman'DB = 'mysql'
DB_HOST = '127.0.0.1'
  1. 在 app.module.ts 文件中全局配置 ConfigModule
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NotificationModule } from './notification/notification.module';@Module({imports: [ConfigModule.forRoot({ isGlobal: true }), // 全局导入 ConfigModuleNotificationModule,],controllers: [],providers: [],
})
export class AppModule {}

isGlobal 设置为 true 时,配置模块会成为全局模块,可以被应用程序的任何模块和组件使用。这意味着你可以在应用程序的任何地方注入 ConfigService,并使用其中定义的变量和值。如果没有设置为全局模块,那么只能在配置模块所在的模块中使用 ConfigService

  1. 在 Controller 中注入 ConfigService 实例并使用:
import { Controller, Get } from '@nestjs/common';
import { ConfigService } from '@nestjs/config/dist';@Controller('notification')
export class NotificationController {constructor(private readonly configService: ConfigService) {} // 注入 ConfigService 实例@Get()getNotification() {// 使用 ConfigService 实例return this.configService.get('TOKEN_SECRET'); // superman}
}

配置多个环境变量文件

  1. npm i cross-env
  2. 配置脚本:
"scripts": {"start:dev": "cross-env NODE_ENV=development nest start --watch","start:prod": "cross-env NODE_ENV=production node dist/main",
},
  1. 创建 .env、.env.development、.env.production 文件用于存储不同环境下的环境变量:
TOKEN_SECRET = 'superman'
DB = 'mysql'
DB = 'dev-mysql'
DB = 'prod-mysql'
  1. 在 app.module.ts 文件中配置 ConfigModule
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NotificationModule } from './notification/notification.module';@Module({imports: [ConfigModule.forRoot({isGlobal: true,// 指定存储环境变量的文件, 靠前的文件拥有较高的优先级envFilePath: [`.env.${process.env.NODE_ENV}`, '.env'],}),NotificationModule,],controllers: [],providers: [],
})
export class AppModule {}
  1. 在 Controller 中注入 ConfigService 实例并使用:
import { Controller, Get } from '@nestjs/common';
import { ConfigService } from '@nestjs/config/dist';@Controller('notification')
export class NotificationController {constructor(private readonly configService: ConfigService) {}@Get()getNotification() {return this.configService.get('DB');// 获取环境变量时, 会按照 `envFilePath` 指定的数组, 从前往后找}
}

现在,就可以通过执行不同的脚本,在不同的环境下,使用对应文件下的环境变量啦~

郁金香