@nestjs/config
NestJS ha incorporado dotenv y lo ha encapsulado en @nestjs/config
npm i @nestjs/config
- Escriba las variables de entorno en el archivo .env:
TOKEN_SECRET = 'superman'
DB = 'mysql'
DB_HOST = '127.0.0.1'
- Configure globalmente en el archivo 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 }), // 全局导入 ConfigModule
NotificationModule,
],
controllers: [],
providers: [],
})
export class AppModule {
}
Cuando isGlobal
se establece true
en , el módulo de configuración se vuelve global y puede ser utilizado por cualquier módulo y componente de la aplicación. Esto significa que puede inyectar en cualquier lugar de su aplicación ConfigService
y usar las variables y valores definidos allí. Si no se configura como un módulo global, solo se puede usar en el módulo donde se encuentra el módulo de configuración ConfigService
.
- Inyecte
ConfigService
la instancia y use:
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
}
}
Configurar varios archivos de variables de entorno
npm i cross-env
- Guión de colocación:
"scripts": {
"start:dev": "cross-env NODE_ENV=development nest start --watch",
"start:prod": "cross-env NODE_ENV=production node dist/main",
},
- Cree archivos .env, .env.development, .env.production para almacenar variables de entorno en diferentes entornos:
TOKEN_SECRET = 'superman'
DB = 'mysql'
DB = 'dev-mysql'
DB = 'prod-mysql'
- Configure en el archivo 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 {
}
- Inyecte
ConfigService
la instancia y use:
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` 指定的数组, 从前往后找
}
}
Ahora, puede usar las variables de entorno en los archivos correspondientes en diferentes entornos ejecutando diferentes scripts ~