2024-10-28-【研发】nestjs环境区分

nestjs

1. 安装涉及工具包

  1. cross-env ^7.0.3
  2. @nestjs/config ^2.3.1

2.创建 env.dev 与 env.prod 文件

写入生产环境变量与开发环境变量

1
2
3
4
5
6
7
8
9
10
DDD_USER=root
DDD_PD=xxx
DDD_HOST=127.0.0.1
DDD_PORT=3306
DDD_NAME='databaseName'
CONSUL_HOST=xxx
CONSUL_PORT=8500
APP_PORT=3000
APP_NAME=microservice-name
APP_HOST=127.0.0.1

3. NODE_ENV 环境变量配置

3.1 开发时

在 package.json 中配置 “start:dev”: “cross-env NODE_ENV=dev nest start –watch”

3.2 生产部署时

这里使用 pm2 创建 nodejs 守护进程

  1. 创建 ecosystem.config.js 文件,执行pm2 init simple
  2. 写入配置如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module.exports = {
apps: [
{
name: 'projectName',
script: 'dist/main.js',
env: {
NODE_ENV: 'prod',
},
env_dev: {
NODE_ENV: 'dev',
},
env_prod: {
NODE_ENV: 'prod',
},
},
],
};
  1. 启动 pm2
    pm2 start ecosystem.config.js --env prod --watch

2. 全局注入 app.module.ts 中

设置 isGlobal: true 后,可在任意模块中使用 ConfigService

1
2
3
4
5
6
7
8
9
10
11
import { ConfigModule, ConfigService } from '@nestjs/config';

const envFilePath = `.env.${process.env.NODE_ENV || 'prod'}`;

@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath,
}),
],})

3.使用时注入 ConfigService

3.1 Controller 控制器中

1
2
3
4
5
6
7
8
9
10
11
12
13
import { ConfigService } from "@nestjs/config";

@Controller("cats")
export class CatsController {
constructor(private readonly config: ConfigService) {
const config = this.config;
console.log(
config.get("APP_NAME"),
config.get("APP_HOST"),
config.get("APP_PORT")
);
}
}

3.2 module 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { Module, OnModuleInit } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";

export class AppModule implements OnModuleInit {
constructor(private readonly config: ConfigService) {}

async onModuleInit() {
const config = this.config;
console.log(
config.get("APP_NAME"),
config.get("APP_HOST"),
config.get("APP_PORT")
);
}
}

2024-10-28-【研发】nestjs环境区分
https://zhangyingxuan.github.io/2024-10-28-【研发】nestjs环境区分/
作者
blowsysun
许可协议