nestjs 多环境配置
这里使用yaml进行多环境配置,需要安装@nestjs/config、js-yaml、@types/js-yaml
js-yaml、@types/js-yaml 主要用来读取yaml文件以及指定类型使用
官方教程:Documentation | NestJS - A progressive Node.js framework
1、下载
npm i --save @nestjs/config
npm i js-yaml
npm i -D @types/js-yaml
2、指定环境变量
在package.json中指定不同命令对应不同的变量
"start": "npm run start:dev", "start:dev": "cross-env NODE_ENV=development nest start --watch", "start:debug": "cross-env NODE_ENV=development nest start --debug --watch", "start:prod": "cross-env NODE_ENV=production node dist/main",
主要修改点:cross-env NODE_ENV=自定义环境
3、新建文件夹config,目录如下
4、编写yml内容
# 开发环境配置
app:
prefix: ''
port: 8080
logger:
# 项目日志存储路径,相对路径(相对本项目根目录)或绝对路径
dir: '../logs'
# 文件相关
file:
# 是否为本地文件服务或cos
isLocal: true
# location 文件上传后存储目录,相对路径(相对本项目根目录)或绝对路径
location: '../upload'
# 文件服务器地址,这是开发环境的配置 生产环境请自行配置成可访问域名
domain: 'http://localhost:8080'
# 文件虚拟路径, 必须以 / 开头, 如 http://localhost:8080/profile/****.jpg , 如果不需要则 设置 ''
serveRoot: '/profile'
# 文件大小限制,单位M
maxSize: 10
# 腾讯云cos配置
cos:
secretId: ''
secretKey: ''
bucket: ''
region: ''
domain: ''
location: ''
# 数据库配置
db:
mysql:
host: '127.0.0.1'
username: 'root'
password: 'yehuozhili'
database: 'nest-admin'
port: 3306
charset: 'utf8mb4'
logger: 'file'
logging: true
multipleStatements: true
dropSchema: false
synchronize: true
supportBigNumbers: true
bigNumberStrings: true
# redis 配置
redis:
host: 'localhost'
password: '*********'
port: 6379
db: 2
keyPrefix: ''
# jwt 配置
jwt:
secretkey: 'you_secretkey'
expiresin: '1h'
refreshExpiresIn: '2h'
# 权限 白名单配置
perm:
router:
whitelist:
[
{ path: '/captchaImage', method: 'GET' },
{ path: '/registerUser', method: 'GET' },
{ path: '/register', method: 'POST' },
{ path: '/login', method: 'POST' },
{ path: '/logout', method: 'POST' },
{ path: '/perm/{id}', method: 'GET' },
{ path: '/upload', method: 'POST' },
]
# 用户相关
# 初始密码, 重置密码
user:
initialPassword: '123456'
5、编写index.ts,主要用来读取配置文件
import { join } from 'path';
import { readFileSync } from 'fs';
import * as yaml from 'js-yaml';
export default () => {
const env = process.env.NODE_ENV || 'development';
return yaml.load(
readFileSync(join(__dirname, `./${env}.yml`), 'utf8'),
) as Record<string, any>;
}
6、根目录找到nest-cli.json文件,主要新增了assets,将yml文件复制到打包dist文件中
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
"**/*.yml"
],
"watchAssets": true,
"deleteOutDir": true
}
}
7、配置configModule
import { Global, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import configurationService from '../config/index';
import {join} from 'path';
@Global()
@Module({
imports: [
ConfigModule.forRoot({
cache: true,
load: [configurationService],
isGlobal: true,
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => {
return ({
type: "mysql",
entities: [join('../',`${__dirname}/**/*.entity{.ts,.js}`)],
autoLoadEntities: true, //自动加载实体
timezone: '+08:00',
...config.get("db.mysql"),
} as TypeOrmModuleOptions)
}
})
],
controllers: [],
providers: [],
exports: [TypeOrmModule, ConfigModule],
})
export class ShareModule { }