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

React项目Vite生产构建报错:无法解析src/indexReact.js

问题分析与解决方案

核心原因

你在vite.config.js中设置了root: 'public',这会将Vite的项目根目录指定为public文件夹。生产构建时,Vite会严格基于这个根目录解析文件路径:index.html里的/src/indexReact.jsx会被解析为public/src/indexReact.jsx,但实际你的src目录在public的上级目录,因此出现路径解析失败的错误。开发服务器能正常运行是因为Vite在开发模式下有宽松的路径处理逻辑,但生产构建会严格校验。

解决方案

方案1:遵循Vite默认目录结构(推荐)

Vite的默认规范是将index.html放在项目根目录,而非public文件夹内,这样无需额外配置root:

  1. 将public/index.html移动到项目根目录(project/index.html)
  2. 修改vite.config.js,删除root: 'public'这一行,配置如下:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  base: '/',
});
  1. 保持index.html中的脚本路径不变:<script type="module" src="/src/indexReact.jsx"></script>,此时路径会基于项目根目录正确解析。

方案2:保留现有目录结构,调整路径配置

如果不想移动index.html,需要调整路径指向并配置Vite的解析规则:

  1. 修改public/index.html中的脚本路径为相对路径:
<script type="module" src="../src/indexReact.jsx"></script>
  1. 更新vite.config.js,添加resolve配置确保Vite能正确解析上级目录的文件:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  root: 'public',
  base: '/',
  resolve: {
    alias: {
      '@': '../src'
    }
  }
});

之后你也可以用别名简化路径,比如写成<script type="module" src="@/indexReact.jsx"></script>。

额外注意事项

  • 你的@vitejs/plugin-react版本是^3.0.0,而Vite 6.x需要更高版本的插件支持,建议升级到^4.0.0或以上,避免版本兼容问题:
    npm install @vitejs/plugin-react@latest --save-dev
    
  • 再次验证生产构建前,先执行npm run build前清理构建缓存:
    rm -rf dist && npm run build
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 03:06:04