跳到正文

环境变量 ​

谁启动进程,谁负责加载 env:Nest 内用 ConfigModule / ConfigService,Nest 外用 Node / dotenv 或环境里已 export 的变量。

Nest 应用内 ​

负责把 .env* 灌进进程的是 ConfigModule(底层仍是 dotenv)。ConfigService 是推荐的读取方式(注入、类型、校验),不是唯一方式;也可以直接 process.env.XXX。

更准确:Nest 里靠 ConfigModule 加载,用 ConfigService(或 process.env)读取。

安装 ​

bash
pnpm add @nestjs/config

启用 ​

在根模块调用 ConfigModule.forRoot()。默认读取应用根目录 .env,并与已有 process.env 合并;同名时运行环境中的值优先。

ts
import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'

@Module({
  imports: [ConfigModule.forRoot({ isGlobal: true })],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

isGlobal: true 后其他模块无需再导入;也可不设全局,在需要配置的模块中显式 imports。

指定多个文件时,用 envFilePath;数组中先出现的优先级更高:

ts
ConfigModule.forRoot({
  envFilePath: ['.env.local', '.env'],
  isGlobal: true,
})

环境文件通常含密钥,不应提交到 Git。

使用 ​

  1. 在 .env 中定义变量
  2. 注入 ConfigService 读取
ts
import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'

@Injectable()
export class AppService {
  constructor(private readonly config: ConfigService) {}

  getApiKey() {
    return this.config.get<string>('API_KEY')
  }
}

get() 在变量不存在时返回 undefined;必需配置用 getOrThrow(),避免缺配置仍继续运行。加载完成后也可 process.env.API_KEY,但结合 DI、类型与校验时优先 ConfigService。

应用初始化前加载 ​

模块顶层代码会在 ConfigModule 初始化前执行。若创建应用之前就需要 .env,可由 Nest CLI 交给 Node 提前加载:

bash
nest start --env-file .env

此时变量在引导前已写入 process.env。

Nest 外 ​

drizzle-kit、脚本、CI 等没有 ConfigModule,要靠:

  • Node --env-file
  • dotenv
  • 或运行环境里已经 export 好的变量

然后用 process.env 读取。

bash
node --env-file=.env ./scripts/migrate.mjs

参考 ​

基于 MIT 许可发布