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

Vite报错:Rollup无法从/app/index.html解析导入index.tsx求助

报错排查:Vite构建React项目时Rollup无法解析import "index.tsx"

报错信息

[vite]: Rollup failed to resolve import "index.tsx" from "/app/index.html"

相关配置与操作

1. vite.config.ts 配置

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import postcssNesting from 'postcss-nesting';

export default defineConfig({
    plugins: [react()],
    build: {
        outDir: "../backend/static",
        emptyOutDir: true,
        sourcemap: true
    },
    server: {
        proxy: {
            "/ask": "http://localhost:5000",
            "/chat": "http://localhost:5000"
        }
    },
    css: {
        postcss: {
            plugins: [
                postcssNesting
            ],
        },
    }
});

2. index.html 脚本标签

原本正常运行的标签:

<script type="module" src="/src/index.tsx"></script>

将路径改为index.tsx后触发报错:

<script type="module" src="index.tsx"></script>

3. Docker构建代码

FROM node:21-alpine as node-builder

ENV APP_PATH="/app"

WORKDIR $APP_PATH
COPY app/frontend .

RUN npm install --verbose
RUN npm run build

COPY --from=node-builder $APP_PATH $APP_PATH/static

已尝试操作

  • 修改index.html中脚本的src路径为index.tsx

问题分析与解决方案

问题根源

  1. 路径解析错误:Vite以index.html所在目录(/app)为根目录解析路径,修改为index.tsx后,Vite会去/app目录查找文件,但你的index.tsx实际在/app/src下,导致找不到。
  2. Docker目录结构映射:从Dockerfile看,app/frontend被复制到/app,所以源码文件位于/app/src,直接写index.tsx指向的是/app/index.tsx,而非目标文件。

解决方案

方案1:恢复正确路径

直接使用相对路径或原有绝对路径指向src下的文件:

<!-- 相对路径 -->
<script type="module" src="./src/index.tsx"></script>
<!-- 或保持原有绝对路径 -->
<script type="module" src="/src/index.tsx"></script>

方案2:配置Vite路径别名(可选)

如果想简化路径,可在vite.config.ts中添加别名配置,方便后续导入:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import postcssNesting from 'postcss-nesting';
import path from 'path';

export default defineConfig({
    plugins: [react()],
    resolve: {
        alias: {
            '@': path.resolve(__dirname, './src') // 别名指向src目录
        }
    },
    // 其余原有配置不变
    build: {
        outDir: "../backend/static",
        emptyOutDir: true,
        sourcemap: true
    },
    server: {
        proxy: {
            "/ask": "http://localhost:5000",
            "/chat": "http://localhost:5000"
        }
    },
    css: {
        postcss: {
            plugins: [
                postcssNesting
            ],
        },
    }
});

之后在index.html中使用别名:

<script type="module" src="@/index.tsx"></script>

方案3:验证Docker目录结构

在Dockerfile中添加目录检查命令,确保文件位置正确:

# 在COPY后添加
RUN ls -la $APP_PATH # 查看当前目录下的文件结构

关键注意事项

  • Vite的路径解析以index.html所在目录为根,绝对路径/xxx从根目录查找,相对路径./xxx从当前文件目录查找。
  • 不要随意修改入口脚本路径,需明确文件实际位置与Vite解析规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:28:16