【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. 在 Controller 中注入 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. 在 Controller 中注入 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` 指定的数组, 从前往后找
    }
}

现在,就可以通过执行不同的脚本,在不同的环境下,使用对应文件下的环境变量啦~


  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JS.Huang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值