npm install @nestjs/config
.env
에 정의된 key/value 환경변수를 process.env
에 할당하고 ConfigService
를 통해 접근할 수 있다.import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'
@Module({
imports: [ConfigModule.forRoot({ isGlobal: true})],
})
export class AppModule {}
.env
에 정의된 환경변수를 불러올 수 있다.import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'
@Module({
imports: [ConfigModule, ...],
providers: [...],
controllder: [...]
})
export class MyModule { }
@Injectable()
export class MyService {
constructor(private readonly configService: ConfigService) { }
async test() {
const baseDir = this.configService.get<string>('BASE_DIR')
console.log(baseDir)
}
}
main.ts
에선 app.get(ConfigService) 를 통해 ConfigService 를 사용할 수 있다.async function bootstrap() {
const app = await NestFactory.create(AppModule)
const configService = app.get(ConfigService)
const port = configService.get('NODE_SERVER_PORT')
await app.listen(port)
}
bootstrap()
import { Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { MongooseModule } from '@nestjs/mongoose'
@Module({
imports : [
MongooseModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
uri: configService.get<string>('MONGODB_URL'),
}),
inject: [ConfigService],
}),
]
})
export class MongoConnectorModule { }