在 NestJS 中,我們可以使用 ConfigModule
模塊來加載自定義配置。
首先,我們需要安裝 @nestjs/config
包:
npm install --save @nestjs/config
然后,在你的應用程序模塊中使用 ConfigModule
:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: '.env', // 可選的,指定環境變量文件的路徑
isGlobal: true, // 可選的,表示配置模塊是否應該是全局的,默認為 true
}),
],
})
export class AppModule {}
在 ConfigModule.forRoot
中,可以使用一些配置選項來指定加載配置的行為和規則。常用的選項包括:
-
envFilePath
: 指定環境變量文件(如.env
)的路徑,可以包含多個不同環境的配置,如.env.production
、.env.test
等,還可以通過process.env.NODE_ENV
環境變量動態加載相應的配置。 -
isGlobal
: 指定是否將配置模塊設置為全局的,如果設置為true
(默認值),則可以在任何地方使用配置服務,否則需要在每個需要使用配置的模塊中引入ConfigModule
。
在配置模塊加載完成后,就可以使用 ConfigService
服務來讀取配置了,例如:
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AppService {
constructor(private configService: ConfigService) {}
getPort(): number {
return this.configService.get<number>('APP_PORT') || 3000;
}
getDatabaseConfig(): { host: string, port: number, username: string, password: string } {
return {
host: this.configService.get<string>('DB_HOST', 'localhost'),
port: this.configService.get<number>('DB_PORT', 5432),
username: this.configService.get<string>('DB_USERNAME', 'admin'),
password: this.configService.get<string>('DB_PASSWORD', 'password'),
};
}
}
以上代碼中,我們使用 ConfigService
服務來讀取了兩個配置項,分別是 APP_PORT
和 DB_*
相關的配置項。如果獲取不到配置項,就會使用指定的默認值。