NestJS Configuration

1,682 阅读1分钟

NestJS Configuration

在 NestJS 项目中使用环境变量

原贴地址

先来看看官方的 Configuration 教程。在这个教程中已经基本符合我们的需求,但是它没有区分开不同的模式。例如我们在前端项目中都会配置 development production 这样的不同的环境变量。

初始化项目

nest new nest-config-demo

安装依赖

cd nest-config-demo
yarn add @nestjs/config
yarn add cross-env -D

创建配置函数

mkdir config
cd config
touch index.ts
import { ConfigModule } from '@nestjs/config';

export default function configGenerator() {
  const mode = process.env.NODE_ENV || 'prod';
  const envFilePath =
    mode === 'dev'
      ? ['.env.development.local', '.env.development', '.env']
      : ['.env.production.local', '.env.production', '.env'];

  return ConfigModule.forRoot({ envFilePath });
}

在主模块中引入

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

import configGenerator from 'config';

@Module({
  // 注入依赖
  imports: [configGenerator()],

  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

创建环境变量文件

touch .env
touch .env.development
touch .env.production

在这些文件中定义自定义的环境变量即可

// .env.development
DATA_BASE = 123456
// .env.production
DATA_BASE = abc

添加命令

为开发模式添加一个启动命令,指定 NODE_ENV=dev

{
    "scripts":{
        "dev":"cross-env NODE_ENV=dev nest start --watch"
    }
}

使用环境变量

例如在一个 controller 中

// src/app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    // 声明
    private readonly configService: ConfigService,
  ) {
    // 使用
    console.log(this.configService.get('DATA_BASE'));
  }

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

也可以在主文件中使用

// src/main.ts

import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);

  const config = app.get(ConfigService);
  console.log('config', config.get('DATA_BASE'));
}
bootstrap();