0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

NestJSでenvをmain.tsで読み込む

Posted at

NestJSで.envを読み込むやり方を失念したためのメモ。

TL;DR

main.tsでapp.get(Service)で読み込むことができる
app.getのargument は String || Service Instanceで対応可能。

Reference

現状のファイル構成とファイル

$ tree
src
|- main.ts
|- config
|    |- configuration.ts]
|-.env
.env
PORT=3000
config/configuration.ts
export default () => ({
  port: parseInt(process.env.PORT, 10) || 3000,
});

main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(300);
}
bootstrap();

変更後のファイル

main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config'; //ここを追記

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalPipes(new ValidationPipe());
 //ここから追記
  const PORT = app.get(ConfigService).get('port')
  // const PORT = app.get('ConfigService').get('port')でもできる。
  await app.listen(PORT);
 //ここmade追記
}
bootstrap();

の記載できます。若干使うことが多々あります。

レポ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?