vue: 路由报错后的处理方式(通常用在打包发布后的报错)

发布时间 2023-04-03 11:39:00作者: wjs0509

        用户在发包前进入了页面(也就是请求到了 index.html ),并且在 index.html 中可以得知将来要请求的异步组件的名字叫 a.js ,当服务器这时候发包,并且清空掉了 a.js 这个资源,改名叫 a1.js 。发包之后用户点击 a.js 对应的组件时,浏览器拿着先前在 index.html 得知的 a.js 这个名字去服务器请求资源就得到了以上的 Loading Chunk Failed 报错。

/* 正则使用'\S'而不是'\d' 为了适配写魔法注释的朋友,写'\d'遇到魔法注释就匹配不成功了。

  * 使用reload方法而不是replace原因是replace还是去请求之前的js文件,会导致循环报错。
  * reload会刷新页面, 请求最新的index.html以及最新的js路径。
  * 直接修改location.href或使用location.assign或location.replace,和router.replace同理, 
  * 在当前场景中请求的依然是原来的js文件,区别仅有浏览器的历史栈。因此必须采用reload.
  */
router.onError(error => {
  const jspattern = /Loading chunk (\d)+ failed/g
  const cssPattern = /Loading CSS chunk (\S)+ failed/g
  const isChunkLoadFailed = error.message.match(jspattern || cssPattern)
  const targetpath = router.history.pending.fullpath
  if (isChunkLoadFailed) {
    window.localstorage.setItem('targetpath', targetpath)
    window.location.reload()
  }
})