[NestJS] Configuration and use of environment variables

@nestjs/config

NestJS has built-in dotenv and encapsulated it into @nestjs/config

  1. npm i @nestjs/config
  2. Write environment variables in the .env file:
TOKEN_SECRET = 'superman'

DB = 'mysql'
DB_HOST = '127.0.0.1'
  1. Configure globally in the app.module.ts file 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 {
    
    }

When isGlobalset trueto , the configuration module becomes global and can be used by any module and component of the application. This means you can inject anywhere in your application ConfigServiceand use the variables and values ​​defined there. If not set as a global module, it can only be used in the module where the configuration module is located ConfigService.

  1. Inject ConfigServicethe instance and 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
    }
}



Configure multiple environment variable files

  1. npm i cross-env
  2. Placement script:
"scripts": {
    
    
    "start:dev": "cross-env NODE_ENV=development nest start --watch",
    "start:prod": "cross-env NODE_ENV=production node dist/main",
},
  1. Create .env, .env.development, .env.production files to store environment variables in different environments:
TOKEN_SECRET = 'superman'
DB = 'mysql'
DB = 'dev-mysql'
DB = 'prod-mysql'
  1. Configure in the app.module.ts file 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. Inject ConfigServicethe instance and 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` 指定的数组, 从前往后找
    }
}

Now, you can use the environment variables under the corresponding files in different environments by executing different scripts~


Guess you like

Origin blog.csdn.net/Superman_H/article/details/130031693