所需依赖
pnpm i @nestjs/config js-yaml lodash
pnpm i @types/js-yaml @types/lodash cross-env -D
目录结构
|- config
| |- config.yaml
| |- config.local.yaml
| |- config.development.yaml
| |- config.development.local.yaml
| |- config.production.yaml
| |- config.production.local.yaml
|- src
| |- common
| |- config.module.ts
| |- app.module.ts
|- .gitignore
|- nest-cli.json
涉及文件
1、package.json
{
"scripts": {
"build": "cross-env NODE_ENV=production nest build",
"start": "cross-env NODE_ENV=development nest start",
"start:dev": "cross-env NODE_ENV=development nest start --watch",
"start:debug": "cross-env NODE_ENV=development nest start --debug --watch",
"start:prod": "node dist/main",
"start:deploy": "node main.js",
},
"dependencies": {
"@nestjs/config": "^4.0.2",
"js-yaml": "^4.1.1",
"lodash": "^4.17.21"
},
"devDependencies": {
"@types/js-yaml": "^4.0.9",
"@types/lodash": "^4.17.21",
"cross-env": "^10.1.0"
}
}
2、config.module.ts
import { join } from 'path'
import jsYaml from 'js-yaml'
import { merge } from 'lodash'
import { Module } from '@nestjs/common'
import { readFileSync, existsSync } from 'fs'
import { ConfigModule as NestConfigModule } from '@nestjs/config'
@Module({
imports: [
NestConfigModule.forRoot({
load: [configuration],
isGlobal: true,
cache: true,
}),
],
})
export class ConfigModule {}
function loadConfig(filePath: string): Record<string, any> {
return existsSync(filePath) ? (jsYaml.load(readFileSync(filePath, 'utf-8')) as Record<string, any>) : {}
}
function configuration() {
const { NODE_ENV = 'development' } = process.env
const CONFIG_DIR_PATH = NODE_ENV === 'development' ? join(process.cwd(), 'config') : __dirname
const YAML_COMMON_CONFIG_PATH = join(CONFIG_DIR_PATH, 'config.yaml')
const YAML_COMMON_CONFIG_LOCAL_PATH = join(CONFIG_DIR_PATH, 'config.local.yaml')
const YAML_ENV_CONFIG_PATH = join(CONFIG_DIR_PATH, `config.${NODE_ENV || 'development'}.yaml`)
const YAML_ENV_CONFIG_LOCAL_PATH = join(CONFIG_DIR_PATH, `config.${NODE_ENV || 'development'}.local.yaml`)
const COMMON_CONFIG = loadConfig(YAML_COMMON_CONFIG_PATH)
const COMMON_CONFIG_LOCAL = loadConfig(YAML_COMMON_CONFIG_LOCAL_PATH)
const ENV_CONFIG = loadConfig(YAML_ENV_CONFIG_PATH)
const ENV_CONFIG_LOCAL = loadConfig(YAML_ENV_CONFIG_LOCAL_PATH)
return merge(COMMON_CONFIG, COMMON_CONFIG_LOCAL, ENV_CONFIG, ENV_CONFIG_LOCAL)
}
3、app.module.ts
import { Module } from '@nestjs/common'
import { ConfigModule } from './common/config.module.ts'
@Module({
imports: [ConfigModule]
})
export class AppModule {}
4、.gitignore
.env.local
*.local.yaml
5、nest-cli.json
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
{ "include": "../package.json", "outDir": "./dist/package.json" },
{ "include": "../pnpm-lock.yaml", "outDir": "./dist/pnpm-lock.yaml" },
{ "include": "../config/config.yaml", "outDir": "./dist" }
],
"deleteOutDir": true,
"builder": "webpack"
},
"generateOptions": {
"flat": false,
"spec": false
}
}
使用介绍
1、service 服务使用
import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
@Injectable()
export class LoginService {
constructor(private readonly configService: ConfigService) {}
public testEnvConfig() {
const dbHost = this.configService.get<string>('database.host','localhost')
}
}
2、main.ts 中使用
import { AppModule } from './app.module'
import { ConfigService } from '@nestjs/config'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
const configService = app.get(ConfigService)
const serverPort = configService.get<number>('server.port', 3000)
await app.listen(serverPort)
console.log('\n--------------------------------------------------')
console.log(`➜ Local: http://localhost:${serverPort}`)
console.log('--------------------------------------------------')
}
bootstrap()