config

config

@nestjs/config

import { ConfigModule } from '@nestjs/config';

app.module.ts

@Module({
  imports: [ConfigModule.forRoot(), ...],
  controllers: [...],
  providers: [...],
})

ConfigModule.forRoot()这里会去读取根目录下的.env 文件

.env

NAME = bowling

app.controller.ts

@Controller()
export class AppController {
  constructor(private readonly appService: AppService, private configService: ConfigService) {}
 
  @Get()
  getHello(): string {
    const NAME = this.configService.get('NAME');
    console.log('NAME', NAME);
 
    return this.appService.getHello();
  }
}

这样就可以获取到 DB,但是目前有个限制,哪里使用 configService,对应的 module 中就要导入
ConfigModule.forRoot(),使用不太方便,在 forRoot 中,通过 isGlobal 属性即可将 configService 变为全局可访问

ConfigModule.forRoot({
  isGlobal: true,
}),