共计 1293 个字符,预计需要花费 4 分钟才能阅读完成。
封装config库,在项目其它app内使用。配合docker部署,效果更好。
// libs/config/src/config.module.ts | |
import { resolve } from 'path'; | |
import { Module } from '@nestjs/common'; | |
import { IConfig } from 'config'; | |
import * as dotenv from 'dotenv'; | |
const path = resolve(__dirname, '..', '..', '..'); | |
dotenv.config(); | |
// config目录放在 apps libs 同级,config内的文件,和config库的配置完全一致 | |
process.env['NODE_CONFIG_DIR'] = resolve(path, 'config'); | |
/* eslint @typescript-eslint/no-var-requires: "off" */ | |
const config = require('config'); | |
config.env.current = process.env.NODE_ENV || 'development'; | |
config.env.app = process.env.NODE_APP_INSTANCE; | |
config.env.isProduction = process.env.NODE_ENV === 'production'; | |
config.env.isProd = | |
process.env.NODE_APP_INSTANCE === 'production' && | |
process.env.NODE_ENV === 'production'; | |
// 这个是挂载一个config目录下的文件路径,方便使用 | |
config.env.wsdl = resolve(path, 'config', 'SMS.wsdl'); | |
const provider = { | |
// 这个地方可以写常量,方便其它地方使用 | |
provide: 'NODE_CONFIG', | |
useValue: config, | |
}; | |
({ | |
providers: [provider], | |
exports: [provider], | |
}) | |
export class ConfigModule {} | |
export type IConfig = IConfig; |
// libs/config/src/index.ts | |
export * from './config.module'; |
// 这个是创建config lib 的时候自动生成的,其它的自动生成的文件都可以删除,这个留着就可以了 | |
{ | |
"extends": "../../tsconfig.json", | |
"compilerOptions": { | |
"declaration": true, | |
"outDir": "../../dist/libs/config" | |
}, | |
"include": ["src/**/*"], | |
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"] | |
} |
注意,使用docker部署时,需要把config目录复制到容器内,因为config目录不会被build到dist中。
正文完