LoginSignup
0
0

More than 3 years have passed since last update.

NestJS 環境毎の設定ファイルの読み込み

Posted at

NestJS 環境毎の設定ファイルの読込

新規プロジェクト作成は下記参照
 https://qiita.com/akasatana12345/items/81d6aade0fd43c045716

モジュールのインストール

 npm i --save @nestjs/config

package.jsonの編集

下記追記

package.json
    "start:local": "NODE_ENV=local nest start --watch",
    "start:develop": "NODE_ENV=develop nest start --watch",

設定ファイルの作成

ルートディレクトリ直下に下記ファイルを新規作成する。
・env/local.env
・env/develop.env

設定ファイルに環境毎の定数を設定

env/local.env
TEST_CONFIG="test local config"
env/develop.env
TEST_CONFIG="test develop config"

実装

src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // 全てのmoduleで使用できるように
      envFilePath: `env/${process.env.NODE_ENV}.env`, // NODE_ENVの値によって読み込むファイルを変更する。
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
src/app.controller.ts
  @Get('config')
  getConfig() {
    return this.appService.getConfig();
  }
src/app.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AppService {
  // コンストラクタ追加
  constructor(private configService: ConfigService) {}

  getHello(): string {
    return 'Hello World!';
  }

  // サービスの関数追加
  getConfig(): string {
    return this.configService.get<string>('TEST_CONFIG');
  }
}

確認

ローカル環境で実行

 npm run start:local

スクリーンショット 2020-07-26 10.03.27.png

開発環境で実行

 npm run start:develop

スクリーンショット 2020-07-26 10.06.08.png

まとめ

環境毎に設定ファイル読み込みを分けてみた。
実際はpackage.jsonにNODE_ENVを設定するのではなく、環境変数で設定する。

上記プロジェクトのソース
 https://github.com/kyosuke12345/nest-config-test

下記記事をみたところ、推奨がされていないっぽいけど、とりあえずこれでよいか。
 https://qiita.com/luigiii/items/af083bafc01e6be5930d
なんか他に方法がある場合はどなたか教えてください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0