Nest.js中配置.env的用法,根据生产环境选择数据库

2,822 阅读3分钟

废话不多说直接上代码,时间仓促内容格式有点乱,能看懂就中。

image.png 分别代表不同生产环境的文件:

dev.yml
# 开发环境配置
app:
  prefix: '/api'
  port: 8081
  swagger: true
  logger:
    # 项目日志存储路径,相对路径(相对本项目根目录)或绝对路径
    dir: '../logs'
  # 文件相关
  file:
    # location 文件上传后存储目录,相对路径(相对本项目根目录)或绝对路径
    location: '../upload'
    # 文件服务器地址,开发环境
    domain: 'http://localhost:8081'
    # 文件虚拟路径, 必须以 / 开头, 如 http://localhost:8081/static/****.jpg  , 如果不需要则 设置 ''
    serveRoot: '/static'
# 数据库配置
db:
  mysql:
    host: 'localhost'
    username: 'root'
    password: '123456'
    database: 'kapok'
    port: 3306
    charser: 'utf8mb4'
    logger: 'advanced-console'
    logging: true
    multipleStatements: true
    dropSchema: false
    synchronize: true
    supportBigNumbers: true
    bigNumberStrings: true

# redis 配置
redis:
  host: 'localhost'
  port: 6379
  db: 0
  keyPrefix: 'nest:'

# jwt 配置
jwt:
  secretkey: 'zANDwNQVFzxlfG9myPxVWAkq4iXJEPhI'
  expiresin: '1h'
  refreshExpiresIn: '2h'
# 权限 白名单配置
perm:
  router:
    whitelist: [{ path: '/api/register', method: 'POST'  }, { path: '/api/login', method: 'POST' }, { path: '/api/perm/{id}', method: 'GET' }, { path: '/api/oss/upload', method: 'POST' }]

# 用户相关
# 初始密码, 重置密码
user:
  initialPassword: 'Q123456'

# 开发环境配置
app:
  prefix: '/api'
  port: 8080
  swagger: true
  logger:
    # 项目日志存储路径,相对路径(相对本项目根目录)或绝对路径
    dir: '../logs'
  # 文件相关, 开发环境
  file:
    # location 文件上传后存储目录,相对路径(相对本项目根目录)或绝对路径
    location: '../upload'
    # 文件服务器地址
    domain: 'http://localhost:8081'
    # 文件虚拟路径, 必须以 / 开头
    serveRoot: '/static'
# 数据库配置
db:
  mysql:
    host: 'localhost'
    username: 'root'
    password: '123456'
    database: 'kapok'
    port: 3306
    charser: 'utf8mb4'
    logger: 'advanced-console'
    logging: true
    multipleStatements: true
    dropSchema: false
    synchronize: true
    supportBigNumbers: true
    bigNumberStrings: true

# redis 配置
redis:
  host: 'localhost'
  port: 6379
  db: 0
  keyPrefix: 'nest:'

# jwt 配置
jwt:
  secretkey: 'zANDwNQVFzxlfG9myPxVWAkq4iXJEPhI'
  expiresin: '1h'
  refreshExpiresIn: '2h'
# 权限 白名单配置
perm:
  router:
    whitelist: [{ path: '/api/register', method: 'POST'  }, { path: '/api/login', method: 'POST' }, { path: '/api/perm/{id}', method: 'GET' }, { path: '/api/oss/upload', method: 'POST' }]

# 用户相关
# 初始密码, 重置密码
user:
  initialPassword: 'Q123456'


# 开发环境配置
app:
  prefix: '/api'
  port: 8082
  swagger: true
  logger:
    # 项目日志存储路径,相对路径(相对本项目根目录)或绝对路径
    dir: '../logs'
  # 文件相关
  file:
    # location 文件上传后存储目录,相对路径(相对本项目根目录)或绝对路径
    location: '../upload'
    # 文件服务器地址
    domain: 'http://localhost:8081'
    # 文件虚拟路径, 必须以 / 开头
    serveRoot: '/static'
# 数据库配置
db:
  mysql:
    host: 'localhost'
    username: 'root'
    password: '123456'
    database: 'kapok'
    port: 3306
    charser: 'utf8mb4'
    logger: 'advanced-console'
    logging: true
    multipleStatements: true
    dropSchema: false
    synchronize: true
    supportBigNumbers: true
    bigNumberStrings: true

# redis 配置
redis:
  host: 'localhost'
  port: 6379
  db: 0
  keyPrefix: 'nest:'

# jwt 配置
jwt:
  secretkey: 'zANDwNQVFzxlfG9myPxVWAkq4iXJEPhI'
  expiresin: '1h'
  refreshExpiresIn: '2h'
# 权限 白名单配置
perm:
  router:
    whitelist: [{ path: '/api/register', method: 'POST'  }, { path: '/api/login', method: 'POST' }, { path: '/api/perm/{id}', method: 'GET' }, { path: '/api/oss/upload', method: 'POST' }]

# 用户相关
# 初始密码, 重置密码
user:
  initialPassword: 'Q123456'

index.ts
import { join } from 'path'
const yaml = require('js-yaml');
const fs   = require('fs');
const configFileNameObj = {
  development :'dev',
  test: 'test',
  production: 'prod'
}

const env = process.env.NODE_ENV



export default () => {
  return yaml.load(fs.readFileSync(join(__dirname, `./${configFileNameObj[env]}.yml`), 'utf8')) as Record<string, any>
}

app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ServeStaticModule, ServeStaticModuleOptions } from '@nestjs/serve-static'
import configuration from './config/index';
import path from 'path'
@Module({
  imports: [
    // 配置模块
    ConfigModule.forRoot({
      cache: true,
      load: [configuration],
      isGlobal: true,
    }),
    //配置数据库链接
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        return {
          type: 'mysql',
          entities: ['dist/**/*.entity{.ts,.js}'],
          keepConnectionAlive: true,
          ...config.get('db.mysql'),
        } as TypeOrmModuleOptions;
      },
    })
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

```里面插件的用法去参考npm

```json
packge.json
"start": "nest start",
    "start:dev": "cross-env NODE_ENV=development nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:test": "cross-env NODE_ENV=test node dist/main",
    "start:prod": "cross-env NODE_ENV=production node dist/main",
  • 不要忘了修改nest-cli.json中的参数,不然编译不通过