@nestjs/config
NestJS には dotenv が組み込まれており、@nestjs/config にカプセル化されています。
npm i @nestjs/config
- 環境変数を .env ファイルに書き込みます。
TOKEN_SECRET = 'superman'
DB = 'mysql'
DB_HOST = '127.0.0.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
。
- コントローラーに
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
}
}
複数の環境変数ファイルを構成する
npm i cross-env
- 配置脚本:
"scripts": {
"start:dev": "cross-env NODE_ENV=development nest start --watch",
"start:prod": "cross-env NODE_ENV=production node dist/main",
},
- .env、.env.development、.env.production ファイルを作成して、さまざまな環境で環境変数を保存します。
TOKEN_SECRET = 'superman'
DB = 'mysql'
DB = 'dev-mysql'
DB = 'prod-mysql'
- 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 {
}
- コントローラーに
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` 指定的数组, 从前往后找
}
}
これで、さまざまなスクリプトを実行することで、さまざまな環境の対応するファイルの下で環境変数を使用できます〜