使用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
相关产品推荐
相关产品推荐

