在 NestJS 中,我們可以使用 ConfigModule 模塊來加載自定義配置。
首先,我們需要安裝 @nestjs/config 包:
npm install --save @nestjs/config
然后,在你的應(yīng)用程序模塊中使用 ConfigModule:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: '.env', // 可選的,指定環(huán)境變量文件的路徑
isGlobal: true, // 可選的,表示配置模塊是否應(yīng)該是全局的,默認(rèn)為 true
}),
],
})
export class AppModule {}
在 ConfigModule.forRoot 中,可以使用一些配置選項(xiàng)來指定加載配置的行為和規(guī)則。常用的選項(xiàng)包括:
-
envFilePath: 指定環(huán)境變量文件(如.env)的路徑,可以包含多個(gè)不同環(huán)境的配置,如.env.production、.env.test等,還可以通過process.env.NODE_ENV環(huán)境變量動(dòng)態(tài)加載相應(yīng)的配置。 -
isGlobal: 指定是否將配置模塊設(shè)置為全局的,如果設(shè)置為true(默認(rèn)值),則可以在任何地方使用配置服務(wù),否則需要在每個(gè)需要使用配置的模塊中引入ConfigModule。
在配置模塊加載完成后,就可以使用 ConfigService 服務(wù)來讀取配置了,例如:
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 服務(wù)來讀取了兩個(gè)配置項(xiàng),分別是 APP_PORT 和 DB_* 相關(guān)的配置項(xiàng)。如果獲取不到配置項(xiàng),就會(huì)使用指定的默認(rèn)值。