如何在React Vite项目的index.html中使用环境变量?
解决Vite项目中index.html访问REACT_APP_前缀环境变量的问题
你当前的问题是CRA中%REACT_APP_ID%的占位符替换逻辑在Vite中不生效,原因是Vite默认不支持这种CRA风格的index.html变量替换,且vite-plugin-environment仅处理源码中的process.env变量,不覆盖index.html的占位符处理。
以下是两种可行的解决方案:
方案一:用Vite内置的index.html变量替换
- 修改Vite配置文件,添加
envPrefix指定环境变量前缀,若仅需处理index.html和源码中的import.meta.env,可移除vite-plugin-environment:
import { defineConfig, splitVendorChunkPlugin } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ envPrefix: 'REACT_APP_', // 指定识别以REACT_APP_开头的环境变量 plugins: [ splitVendorChunkPlugin(), react(), ], })
- 在index.html的内联脚本中继续使用
%REACT_APP_ID%占位符:
<script> //Set your APP_ID const APP_ID = '%REACT_APP_ID%' // ...其他代码 </script>
方案二:直接使用Vite的import.meta.env
这是更贴合Vite生态的方式,无需占位符:
- 同样在Vite配置中添加
envPrefix: 'REACT_APP_' - 修改index.html中的脚本:
<script> //Set your APP_ID const APP_ID = import.meta.env.REACT_APP_ID // ...其他代码 </script>
注意:确保环境变量已正确配置,比如在项目根目录的.env文件中添加REACT_APP_ID=你的实际ID,或在启动命令中临时设置(如REACT_APP_ID=xxx npm run dev)。
内容的提问来源于stack exchange,提问作者Don J
相关产品推荐
相关产品推荐

