[NestJS] Configuración y uso de variables de entorno

@nestjs/config

NestJS ha incorporado dotenv y lo ha encapsulado en @nestjs/config

  1. npm i @nestjs/config
  2. Escriba las variables de entorno en el archivo .env:
TOKEN_SECRET = 'superman'

DB = 'mysql'
DB_HOST = '127.0.0.1'
  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 isGlobalse establece trueen , 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 ConfigServicey 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.

  1. Inyecte ConfigServicela 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

  1. npm i cross-env
  2. 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",
},
  1. 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'
  1. 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 {
    
    }
  1. Inyecte ConfigServicela 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 ~


Supongo que te gusta

Origin blog.csdn.net/Superman_H/article/details/130031693
Recomendado
Clasificación