You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NX Monorepo中配置多环境.env文件(Nest.js项目)

解决NX Monorepo中Nest.js应用自定义多环境.env配置问题

1. 规范项目结构

给每个Nest.js应用创建独立的environment文件夹,存放各环境配置文件:

apps/be-license-server/
├── environment/
│   ├── local.env
│   ├── dev.env
│   └── prod.env
├── src/
├── project.json
└── webpack.config.js

2. 修改project.json配置

在build和serve的环境配置中指定对应env文件,同时将environment目录加入静态资源打包列表,确保运行时能读取到文件:

{
  "name": "be-license-server",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "apps/be-license-server/src",
  "projectType": "application",
  "targets": {
    "build": {
      "executor": "@nx/webpack:webpack",
      "outputs": ["{options.outputPath}"],
      "defaultConfiguration": "production",
      "options": {
        "target": "node",
        "compiler": "tsc",
        "outputPath": "dist/apps/be-license-server",
        "main": "apps/be-license-server/src/main.ts",
        "tsConfig": "apps/be-license-server/tsconfig.app.json",
        "assets": [
          "apps/be-license-server/src/assets",
          {
            "input": "apps/be-license-server/environment",
            "output": "./environment",
            "glob": "*.env"
          }
        ],
        "isolatedConfig": true,
        "webpackConfig": "apps/be-license-server/webpack.config.js"
      },
      "configurations": {
        "development": {
          "define": {
            "process.env.NODE_ENV": "\"development\""
          },
          "envFile": "apps/be-license-server/environment/dev.env"
        },
        "production": {
          "define": {
            "process.env.NODE_ENV": "\"production\""
          },
          "envFile": "apps/be-license-server/environment/prod.env"
        },
        "local": {
          "define": {
            "process.env.NODE_ENV": "\"local\""
          },
          "envFile": "apps/be-license-server/environment/local.env"
        }
      }
    },
    "serve": {
      "executor": "@nx/js:node",
      "defaultConfiguration": "local",
      "options": {
        "buildTarget": "be-license-server:build"
      },
      "configurations": {
        "local": {
          "buildTarget": "be-license-server:build:local",
          "envFile": "apps/be-license-server/environment/local.env"
        },
        "development": {
          "buildTarget": "be-license-server:build:development",
          "envFile": "apps/be-license-server/environment/dev.env"
        },
        "production": {
          "buildTarget": "be-license-server:build:production",
          "envFile": "apps/be-license-server/environment/prod.env"
        }
      }
    },
    "lint": {
      "executor": "@nx/linter:eslint",
      "outputs": ["{options.outputFile}"],
      "options": {
        "lintFilePatterns": ["apps/be-license-server/**/*.ts"]
      }
    }
  },
  "tags": ["prisma"]
}

3. Webpack编译时注入环境变量(可选)

如果需要在编译阶段将env变量注入代码,使用dotenv-webpack插件:

  1. 安装依赖
npm install dotenv-webpack --save-dev
  1. 修改webpack.config.js
const { composePlugins, withNx } = require('@nx/webpack');
const Dotenv = require('dotenv-webpack');
const path = require('path');

module.exports = composePlugins(withNx(), (config, { options, context }) => {
  const envPath = path.resolve(__dirname, `environment/${context.configuration || 'local'}.env`);
  config.plugins.push(new Dotenv({ path: envPath }));
  return config;
});

4. Nest.js应用中读取环境变量

有两种读取方式:

  • 编译时注入的变量直接用process.env.XXX调用
  • 运行时动态加载(适合切换环境),用dotenv包:
    1. 安装依赖
    npm install dotenv
    
    1. 在main.ts中加载
    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import * as dotenv from 'dotenv';
    import * as path from 'path';
    
    async function bootstrap() {
      const env = process.env.NODE_ENV || 'local';
      dotenv.config({ path: path.join(__dirname, `../environment/${env}.env`) });
    
      const app = await NestFactory.create(AppModule);
      await app.listen(process.env.PORT || 3000);
    }
    bootstrap();
    

5. 运行命令示例

  • 本地开发启动:nx serve be-license-server --configuration=local
  • 开发环境构建:nx build be-license-server --configuration=development
  • 生产环境启动:nx serve be-license-server --configuration=production

内容的提问来源于stack exchange,提问作者Elias Salom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:53:12