Skip to content

Vue项目中出现Loading chunk {n} failed问题的解决方法

更新:2024-01-09 at 16:43

Vue项目中会偶尔出现Loading chunk {n} failed的报错,报错来自于webpack进行code spilt之后某些bundle文件lazy loading失败

原因分析

解决方法

  1. 让html页面每次加载不走缓存,增加禁用缓存的meta标签
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
  1. 捕获到此异常错误时,可根据自己的业务场景选择:
// 强制刷新页面
function forceReloadPage() {
  // 设置只强制刷新一次页面,防止死循环刷新
  if (!sessionStorage.getItem("forceReloadPage")) {
    sessionStorage.setItem("forceReloadPage", "RELOADED");
    window.location.reload(true);
  }
}

// vue-router中监听错误
router.onError(error => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  if (isChunkLoadFailed) {
    // 命中错误,可根据自己的业务场景实现交互方案
    forceReloadPage();
  }
});

扩展

vue项目,可以通过框架提供的api捕获到错误进行处理。或者下面更通用的方案:

// 强制刷新页面
function forceReloadPage() {
  // 设置只强制刷新一次页面,防止死循环刷新
  if (!sessionStorage.getItem("forceReloadPage")) {
    sessionStorage.setItem("forceReloadPage", "RELOADED");
    window.location.reload(true);
  }
}
window.addEventListener(
  "error",
  function (error) {
    const pattern = /Loading chunk (\d)+ failed/g;
    const isChunkLoadFailed = error.message.match(pattern);
    if (isChunkLoadFailed) {
      // 命中错误,可根据自己的业务场景实现交互方案
      forceReloadPage();
    }
  },
  true
);