【已解决】Vite 部署后报错:Failed to fetch dynamically imported module

问题描述:

使用Vite打包构建的项目,重新部署到生产。在部署期间用户一直停留在当前项目页面,部署完成后点击页面上的路由,报错! 刷新后恢复正常。

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

TypeError: Failed to fetch dynamically imported module: xxx/assets/index-4f5b61b3.js

在Vite的github找到下面这个issue,一模一样的问题

github.com/vitejs/vite...

Since switching to Vite we noticed a new production issue, where sometimes users are encountering an error if we deploy while they have an active session:

这个issue留言还比较多,同时也找到了解决方法:

js 复制代码
// Hard-reload the page when chunk load errors match the navigation error
const routerInstance = router();
routerInstance.onError((error, to) => {
  const errors = ['Failed to fetch dynamically imported module', 'Unable to preload CSS'];

  if (errors.some((e) => error.message.includes(e))) {
    window.location = to.fullPath;
  }
});
相关推荐
Heo10 小时前
大厂前端调试不能只会debugger
前端·javascript·面试
用户21816970493010 小时前
Flutter (十七) 网络请求
前端
cidy_9810 小时前
React 19 + Vite 企业级前端项目:从零搭建到规范交付
前端
用户9210802628610 小时前
如何把一张图片做成自定义复杂 UI 图标
前端
用户9385156350711 小时前
从 0 拆解一个 Next.js 笔记系统:npx、App Router、RSC 与组件规划全记录
前端·后端·全栈
hello930711 小时前
plop代码生成器
前端
windliang11 小时前
Claude Code 源码分析(十二):错误处理与自动恢复:让 Agent 稳定运行
前端·javascript·面试
fatcoder11 小时前
玩转Docker 06 — 容器网络
前端·后端·docker
打呵欠的猫11 小时前
我用 AI 重写了项目的请求层,从 800 行"面条代码"变成 3 层洋葱模型
前端·ai编程
默_笙11 小时前
🛬 前端路由的"高级玩法":懒加载、404、鉴权路由,一个都不能少(下篇)
前端·javascript