DEBUG.WIKI
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →

解决 Vite 报错 import.meta.glob failed to resolve dynamic import 动态匹配修复

排查 Vite 在生产构建时报 Error: Cannot find module 或 import.meta.glob failed to resolve,开发环境正常但 build 后静态路由白屏,分析 动态导入通配符规则与 Rollup 打包分析。

问题现象

使用 import.meta.glob 自动注册视图路由时,vite dev 本地开发一切正常,但在 vite build 生产构建后运行时页面白屏:

TypeError: Failed to fetch dynamically imported module: /src/views/Dashboard/index.vue
Error: Cannot find module './views/Dashboard/index.vue'

触发根因

  1. import.meta.glob 在静态构建期必须依赖能够确定物理文件的通配符表达式;
  2. 使用了包含未定义运行时变量的字符串拼接(如 import.meta.glob('@/views/' + path + '.vue')),Rollup 无法在编译期完成依赖图静态推断;
  3. 通配符路径以别名(如 @/)开头,部分 Vite 插件版本无法正确解析非相对路径的前缀。

解决步骤

使用规范的相对路径编写静态通配符表达式

避免在 glob 入参中使用变量:

// 规范写法:必须以 ./ 或 ../ 开头
const modules = import.meta.glob('./views/**/*.vue');

export function getComponent(path: string) {
  const normalizedPath = `./views/${path}.vue`;
  return modules[normalizedPath] ? modules[normalizedPath]() : null;
}

对于关键基础路由可开启 eager 同步加载

避免过多细碎网络请求:

const staticViews = import.meta.glob('./views/*.vue', { eager: true });

检查构建输出产物目录

确保没有被 .gitignore 规则意外忽略。

验证确认

重新执行 vite build && vite preview:

所有页面组件被平滑打包并按需分块,生产环境路由跳转顺畅无阻断。