解决 Vite 构建报错 Rollup failed to resolve import 模块缺失
在 Vite 开发正常但运行 vite build 生产打包时报错 [vite]: Rollup failed to resolve import ... from ...。本文深入剖析开发时 esbuild 与生产时 Rollup 的解析差异、路径别名配置及扩展名补全方案。
问题现象
项目在执行 npm run dev(Vite 本地开发服务器)时页面运行完全正常,但一运行 npm run build 构建生产包时,终端报错中断:
[vite]: Rollup failed to resolve import "@/components/Header" from "src/views/Home.vue".
This is most likely unintended because it can also happen should the file exist on disk
because of the case sensitivity of the file system.
error during build:
Error: [vite]: Rollup failed to resolve import "@/components/Header" from "src/views/Home.vue".
触发根因
- 开发与生产解析器行为差异:Vite 在本地开发时依赖浏览器原生 ES Modules 并由 esbuild 进行极其宽容的预构建;而在生产打包时则切换为 Rollup。Rollup 默认对文件扩展名、绝对路径与别名要求极为严格。
- 路径别名(Alias)未在 vite.config 中映射:在 TypeScript
tsconfig.json中配置了"@/*": ["src/*"],IDE 代码跳转正常,但未在vite.config.ts中同步配置resolve.alias。 - 大小写敏感性问题(Case Sensitivity):开发机器处于 macOS/Windows(默认不区分文件名大小写),代码中写的是
Header,而实际磁盘文件名为header.vue。本地开发能读出文件,但当推送到 Linux 容器(CI/CD)或 Rollup 严格模式下,立即发生找不到文件错误。 - 缺少扩展名自动推断:导入
.vue或其他自定义后缀单文件组件时省略了后缀名,而 Rollup 默认仅解析.js,.jsx,.ts,.tsx。
诊断排查步骤
1. 检查物理文件名大小写
在终端中通过原生命令查看实际文件名:
ls -la src/components/
对比代码中的 import ... from '@/components/xxx' 是否与磁盘文件名字符大小写完全一致。
2. 检查 vite.config 中的 resolve.alias 配置
检查配置文件中是否包含对 @ 字符的路径解析。
解决方案
方案一:在 vite.config.ts 中规范化路径别名配置
使用 Node 的 path.resolve 或 fileURLToPath(ESM 规范)声明别名:
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { fileURLToPath, URL } from 'node:url';
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
// 若导入 .vue 组件省略了扩展名,需显式声明:
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
}
});
方案二:确保导入单文件组件带有显式扩展名
由于 Vue 单文件组件不属于 ECMAScript 标称文件,Vite 官方推荐在导入 Vue 组件时显式保留 .vue 后缀:
// 规范:明确写上 .vue
import Header from '@/components/Header.vue';
方案三:排查第三方依赖的模块入口定义(package.json exports)
如果解析失败的是某个 npm 包(如 import { util } from 'my-lib/dist/helpers'):
该包的 package.json 可能声明了 "exports" 字段且限制了子路径访问。此时应按照该包官方文档导入公开导出的子模块,或在 vite.config.ts 的 optimizeDeps.include 中将其显式加入预构建。
验证方法
执行生产打包命令:
npm run build
输出应展示模块转换与打包详情:
vite v4.4.9 building for production...
✓ 142 modules transformed.
dist/index.html 0.45 kB │ gzip: 0.30 kB
dist/assets/index-8a21f7e0.js 145.20 kB │ gzip: 42.15 kB
✓ built in 1.12s
退出码为 0 且 dist/ 成功生成产物,即表示解析故障根除。


