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

使用NX构建React应用时Vite环境变量丢失问题求助

Nx + Vite Monorepo 环境变量构建丢失问题

我正在使用Nx和Vite开发一个monorepo项目,针对不同部署环境配置了多个.env文件:

  • .env.dev
  • .env.stg(预发布环境)
  • .env.prod(生产环境)

问题:开发阶段能正常获取环境变量,但构建部署到测试环境时,打包成功后产物中完全找不到环境变量的痕迹。所有环境变量均按要求添加了VITE_前缀。


相关配置文件

1. vite.config.ts(路径:app/<name>/src)

import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import dts from 'vite-plugin-dts'
import * as path from 'path'
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin'

export default defineConfig(({ mode }) => {
  process.env = { ...process.env, ...loadEnv(mode, process.cwd()) }

  return {
    root: __dirname,
    ...(process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'development'
      ? {
          define: {
            global: {},
          },
        }
      : {}),
    cacheDir: '../node_modules/.vite/api',

    plugins: [
      react(),
      nxViteTsPaths(),
      dts({
        entryRoot: 'src',
        tsConfigFilePath: path.join(__dirname, 'tsconfig.lib.json'),
        skipDiagnostics: true,
      }),
    ],

    // Uncomment this if you are using workers.
    // worker: {
    //  plugins: [ nxViteTsPaths() ],
    // },

    // Configuration for building your library.
    build: {
      outDir: '../dist/api',
      reportCompressedSize: true,
      commonjsOptions: { transformMixedEsModules: true },
      entry: 'src/index.ts',
      name: 'api',
      fileName: 'index',
      formats: ['es', 'cjs'],
      external: ['react', 'react-dom', 'react/jsx-runtime'],
      lib: {
        entry: 'src/index.ts',
        name: 'api',
        fileName: 'index',
        formats: ['es', 'cjs'],
      },
      rollupOptions: {
        external: ["'react'", "'react-dom'", "'react/jsx-runtime'"]
      },
    },
  }
})

2. project.json(同目录)

{
  "name": "n360-portal",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "apps/n360-portal/src",
  "projectType": "application",
  "targets": {
    "build": {
      "executor": "@nx/vite:build",
      "outputs": ["{options.outputPath}"],
      "defaultConfiguration": "production",
      "options": {
        "outputPath": "dist/apps/n360-portal"
      },
      "configurations": {
        "development": {
          "mode": "dev"
        },
        "production": {
          "mode": "prod"
        },
        "staging": {
          "mode": "stg"
        },
        "int": {
          "mode": "int"
        }
      }
    },
    "serve": {
      "executor": "@nx/vite:dev-server",
      "defaultConfiguration": "development",
      "options": {
        "buildTarget": "n360-portal:build"
      },
      "configurations": {
        "development": {
          "buildTarget": "n360-portal:build:development",
          "hmr": true,
          "mode": "dev"
        },
        "staging": {
          "buildTarget": "n360-portal:build:staging",
          "hmr": true,
          "mode": "stg"
        },
        "int": {
          "buildTarget": "n360-portal:build:int",
          "hmr": true,
          "mode": "int"
        },
        "production": {
          "buildTarget": "n360-portal:build:production",
          "hmr": true,
          "mode": "prod"
        }
      }
    },
    "preview": {
      "executor": "@nx/vite:preview-server",
      "defaultConfiguration": "development",
      "options": {
        "buildTarget": "n360-portal:build"
      },
      "configurations": {
        "development": {
          "buildTarget": "n360-portal:build:development"
        },
        "staging": {
          "buildTarget": "n360-portal:build:staging"
        },
        "int": {
          "buildTarget": "n360-portal:build:int"
        },
        "production": {
          "buildTarget": "n360-portal:build:production"
        }
      }
    },
    "test": {
      "executor": "@nx/vite:test",
      "outputs": ["{options.reportsDirectory}"],
      "options": {
        "passWithNoTests": true,
        "reportsDirectory": "../../coverage/apps/n360-portal"
      }
    },
    "lint": {
      "executor": "@nx/eslint:lint",
      "outputs": ["{options.outputFile}"]
    },
    "serve-static": {
      "executor": "@nx/web:file-server",
      "options": {
        "buildTarget": "n360-portal:build"
      }
    }
  },
  "tags": []
}

3. bitbucket-pipelines.yml

image: node:20

definitions:
  caches:
    pnpm: $BITBUCKET_CLONE_DIR/.pnpm-store
  steps:
    - step: &Build
        name: Build 
        caches:
          - node
          - pnpm
        script:
          - make install-deps-build
    - step: &Build-Deploy
        name: Build and deploy
        caches:
          - node
          - pnpm
        script:
          - make build-deploy
          - echo "VITE_API_URL=$VITE_API_URL" 
          - echo "VITE_DOCS_LINK=$VITE_DOCS_LINK" 
          - echo "VITE_STATUS_LINK=$VITE_STATUS_LINK" 
          - echo "VITE_COGNITO_REGION=$VITE_COGNITO_REGION"
          - echo "VITE_COGNITO_USER_POOL_ID=$VITE_COGNITO_USER_POOL_ID"
          - echo "VITE_COGNITO_USER_POOL_WEB_CLIENT_ID=$VITE_COGNITO_USER_POOL_WEB_CLIENT_ID" 
          - echo "VITE_FUSION_CHART_LICENSE_KEY=$VITE_FUSION_CHART_LICENSE_KEY" 
          - echo "VITE_PUBLIC_API_URL=$VITE_PUBLIC_API_URL"
          - echo "VITE_PORTAL_URL=$VITE_PORTAL_URL" 
          - echo "VITE_RECAPTCHA_SITE_KEY=$VITE_RECAPTCHA_SITE_KEY" 
          - echo "VITE_RECAPTCHA_KEY=$VITE_RECAPTCHA_KEY" 
          - pnpm exec nx run n360-portal:build:$DEPLOY_ENV --verbose

          - pipe: atlassian/aws-s3-deploy:0.4.4
            variables:
              AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
              AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
              AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
              S3_BUCKET: $AWS_S3_Bucket
              LOCAL_PATH: 'dist/apps/n360-portal/'
          - pipe: atlassian/aws-cloudfront-invalidate:0.6.0
            variables:
              AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
              AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
              AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
              DISTRIBUTION_ID: $CLOUDFRONT_DISTRIBUTION_ID
        artifacts:
          - dist/**
pipelines:
  pull-requests:
    '**':
      - step: *Build
  branches:
    'development':
      - step: *Build
      - step: 
          name: Build and deploy
          deployment: development
          <<: *Build-Deploy
    'staging':
      - step: *Build
      - step: 
          name: Build and deploy
          deployment: master
          <<: *Build-Deploy
    'production':
      - step: *Build
      - step: 
          name: Build and deploy
          deployment: production
          <<: *Build-Deploy

已尝试的方案:

  • 将所有配置合并到单个.env文件
  • 重构vite.config.ts仅返回defineConfig对象

以上方案均未解决问题,Nx文档及相关讨论中也缺乏有效解决方案,请求帮助。

内容的提问来源于stack exchange,提问作者Olivier Papineau

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 15:02:32