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

React CRA项目迁移Vite后构建仅生成index.html问题排查

问题分析与解决方案

核心原因

你当前的Vite配置把root设为了src目录,这不符合Vite的默认入口规则:

  1. Vite默认以项目根目录下的index.html作为构建入口,而非src目录;
  2. 若root指向src,Vite会在src下寻找index.html,若找不到则生成一个空的默认html文件,且没有关联任何业务代码入口(比如main.tsx),最终导致构建仅输出空的index.html。

同时,你还遗漏了Vite对@/*路径别名的配置,虽然这不是当前构建空输出的直接原因,但后续会导致模块导入失败。

解决步骤

1. 调整Vite配置文件

修改vite.config.ts,移除root配置,添加路径别名和public目录配置:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  // 配置@/*路径别名,对应tsconfig中的paths
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  build: {
    outDir: 'build', // 保持与CRA一致的输出目录
  },
  publicDir: 'public', // 指定静态资源目录,对应CRA的public文件夹
});

2. 调整入口HTML文件

将原CRA项目中public/index.html移动到项目根目录(或直接在根目录新建),并在其中添加业务代码入口的引用:

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!-- 关键:引入你的React入口文件,路径对应src下的main.tsx/jsx -->
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

3. 验证tsconfig配置

确保你的tsconfig.json中noEmit保持true(Vite会负责代码编译,tsc仅做类型检查),其他配置无需改动。

4. 重新执行构建

运行pnpm run build,此时应该会正常生成包含JS/CSS资源的build目录。

额外注意事项

  • 若项目中使用了process.env环境变量,需要安装vite-plugin-env-compatible插件来兼容CRA的环境变量写法;
  • 若需要兼容旧浏览器,可添加@vitejs/plugin-legacy插件配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:35:33