一聚教程网:一个值得你收藏的教程网站

热门教程

vue-cli 打包后提交到线上出现 "Uncaught SyntaxError:Unexpected token" 报错

时间:2022-06-25 15:29:08 编辑:袖梨 来源:一聚教程网

前言: 项目使用vue-cli版本2.9.3 ,vue-router使用webpackChunkName实现按需加载.

BUG描述:该报错在项目上线一段时间后,有用户反映页面无法正常游览 (后面以问题1/问题2区分)

问题1.导航点击无法正常跳转,console打印:Error:Loading chunk {n} failed.

报错截图

问题2.页面全白,console打印:Uncaught SyntaxError:Unexpected token <

报错截图:

经过一番折腾,初步定位问题1在经过build/webpack.prod.conf.jschunkhash打包后的JS文件hash值会有变更,因为每次更新代码到线上都会删除旧的dist目录,将最新的dist目录copy上传提供后台更新. 在更新代码的这个过程用户停留在页面上,当用户在更新完后重新操作就会导致报错

问题1解决方法:捕获路由报错. (思路来源:https://www.jb51.net/article/147427.htm)

routers.onError((err) => {
 const pattern = /Loading chunk (d)+ failed/g;
 const isChunkLoadFailed = err.message.match(pattern);
 if (isChunkLoadFailed) {
  let chunkBool = sessionStorage.getItem('chunkError');
  let nowTimes = Date.now();
  if (chunkBool === null || chunkBool && nowTimes - parseInt(chunkBool) > 60000) {//路由跳转报错,href手动跳转
   sessionStorage.setItem('chunkError', 'reload');
   const targetPath = routers.history.pending.fullPath;
   window.location.href = window.location.origin + targetPath;
  }else if(chunkBool === 'reload'){ //手动跳转后依然报错,强制刷新
   sessionStorage.setItem('chunkError', Date.now());
   window.location.reload(true);
  }
 }
})

问题2在Network查看js文件加载的时候发现某个js文件Response Headercontent-type异常,正常情况返回content-type: application/javascript. 但是有一个js响应的内容为HTML, js无法识别<符号导致抛出报错

问题2目前还在与后台商量如何解决,解决后会更新解决方法分享.有同学遇到同样的问题可以一起讨论或提出更好的解决方案参考学习.★★★

热门栏目