[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 }), // 全局导入 ConfigModule
        NotificationModule,
    ],
    controllers: [],
    providers: [],
})
export class AppModule {
    
    }

isGlobalに設定するtrue、構成モジュールはグローバルになり、アプリケーションの任意のモジュールおよびコンポーネントで使用できます。これは、アプリケーションのどこにでも注入できConfigService、そこで定義された変数と値を使用できることを意味します。グローバルモジュールとして設定されていない場合、構成モジュールが配置されているモジュールでのみ使用できますConfigService

  1. コントローラーに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. コントローラーに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` 指定的数组, 从前往后找
    }
}

これで、さまざまなスクリプトを実行することで、さまざまな環境の対応するファイルの下で環境変数を使用できます〜


おすすめ

転載: blog.csdn.net/Superman_H/article/details/130031693