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

使用Vite在React项目index.html中替换环境变量时遇报错

解决Vite中index.html环境变量插值报错问题

问题现象

使用Vite搭建的React项目中,在index.html里使用%REACT_APP_BACKEND_URL%插值环境变量时,出现报错:

(!) %REACT_APP_BACKEND_URL% is not defined in env variables found in /index.html. Is the variable mistyped?

已确认.env.development.local中的变量能通过console.log正常打印,但HTML中的插值不生效。

问题原因

你的Vite配置中将root设为src,且index.html放在了src目录下,但Vite仅会自动解析public目录下HTML文件中的%变量名%格式环境变量,src目录下的HTML不会触发这个插值逻辑。

解决方案

1. 调整index.html位置

  • 将src目录下的index.html移动到配置指定的public目录(即项目根目录下的public文件夹)。
  • 修改index.html中的入口脚本路径,原路径src="index.jsx"需改为src="/src/index.jsx",确保指向正确的入口文件。

调整后的index.html示例:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="refferer" content="strict-origin-when-cross-origin" />
    <link rel="dns-prefetch" href="%REACT_APP_BACKEND_URL%" />
  </head>

  <body>
    <div class="ac-content">
      <noscript> You need to enable JavaScript to run this app. </noscript>
      <div id="root"></div>
      <script type="module" src="/src/index.jsx"></script>
    </div>
  </body>
</html>

2. 简化Vite配置(可选)

你的define配置可以简化,直接将loadEnv返回的对象赋值给process.env,无需额外reduce处理:

/* eslint-disable import/extensions */
/* eslint-disable import/no-extraneous-dependencies */
import { defineConfig, loadEnv } from 'vite'
import svgr from 'vite-plugin-svgr'
import tsconfigPaths from 'vite-tsconfig-paths'
import react from '@vitejs/plugin-react'

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

  return {
    define: {
      'process.env': env
    },
    root: 'src',
    build: {
      outDir: '../dist'
    },
    envPrefix: 'REACT_APP_',
    base: './',
    plugins: [
      react(),
      svgr(),
      tsconfigPaths({ root: '../' }),
    ],
    publicDir: '../public'
  }
})

3. 验证

重启Vite开发服务,此时public目录下的index.html中的环境变量会被正确插值,报错消失。

补充说明

  • JS代码中通过process.env.REACT_APP_*访问变量是依靠define配置实现的,和HTML中的%变量%插值是两个独立的逻辑,前者不受HTML文件位置影响。
  • 若不想移动index.html,可通过自定义Vite插件实现HTML插值,但将HTML放在public目录是官方推荐的最简方案。

内容的提问来源于stack exchange,提问作者João Fernandes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:35:29