问题记录
Uncaught SyntaxError: Unexpected token '<' (at chunk-29567c98.1.1.7.1714119572090.js:1:1)
1.在webpack打包中配置
(1)编写方法 以时间戳为版本号 配置并写入公共资源下的版本文件号
function getVersion(){
version = {
version: Timestamp,
}
fs.writeFile('./public/version.json', JSON.stringify(version), function(err) {
if(err) {
console.log(err)
}else{
console.log('version.json 写入成功',JSON.stringify(version))
}
})
}
(2)在 chainWebpack 中配置
config.when(process.env.NODE_ENV !== "development", (config) => {
//.....
getVersion()
//....你的其余配置逻辑
});
2.建立文件 autoUpdate.js
import axios from "axios";
import Cookies from "js-cookie";
axios.defaults.headers["Cache-Control"] = "no-cache";
let hidden = false
let currentVersion;
let lastVersion;
let setTimeouts;
export const checkOutVersion = async () => {
lastVersion = Cookies.get('version')
await getVersion().then(res => {
currentVersion = res.data.version
})
if (Number(lastVersion) !== Number(currentVersion)) {
// Cookies.get('version', currentVersion)
Cookies.set('version',currentVersion)
setTimeout(()=>{
window.location.href = window.location.href
},1000)
}
}
//获取版本号
export const getVersion = ()=>{
return axios.get(`http://${window.location.host}/version.json`)
}
const start = async () => {
await getVersion().then(res => {
currentVersion = res.data.version
})
if (!Cookies.get('version')) {
Cookies.set('version', currentVersion)
}
setTimeouts = setInterval(() => {
setTimeout(() => {
checkOutVersion()
},0)
},60000)
}
const stop = () => {
if(setTimeouts){
clearInterval(setTimeouts)
setTimeouts = ''
}
}
const watchHiden = ()=>{
if(setTimeouts){
stop()
}
start()
// window.addEventListener('visibilitychange',()=>{//监听浏览器标签页隐藏 显示
// hidden = document.hidden
// console.log(hidden,'版本检测')
// if (!hidden) {
// start()
// }else{
// stop()
// }
// })
}
export default watchHiden
3.路由前置守卫设置
await getVersion().then((res) => {
if (!Cookies.get("version")) {
Cookies.set("version", res.data.version);
} else {
if (Number(Cookies.get("version")) != Number(res.data.version)) {
Cookies.set("version", res.data.version);
setTimeout(()=>{
window.location.href = window.location.href // 模拟Crtl+F5清理缓存
},1000)
}
}
});
4.在app.vue 设置
mounted(){
watchHiden()
}
方法2 直接在app.vue 中捕获错误代码
const head = document.getElementsByTagName('head')[0]
head.addEventListener('DOMNodeInserted', e => {
// 获取标签名
const type = e.target.tagName
// 获取资源路径
const url = e.target.src
if (type === 'SCRIPT' && url) {
// 创建请求,如果需要低版本浏览器兼容的,请注意
let xhr = new XMLHttpRequest()
xhr.open('get', url)
xhr.onload = () => {
const text = xhr.responseText
if (text.indexOf('<') === 0) {
this.$message.success('检测到有新的版本发布,需要刷新页面以访问最新内容,页面将在 1 秒后自动刷新')
setTimeout(() => {
location.reload()
}, 1000)
// this.$modal.info({
// title: '检测到有新的版本发布,需要刷新页面以访问最新内容',
// width: 350,
// okText: '确定',
// onOk() {
// location.reload()
// }
// })
}
}
xhr.send()
}
Comments NOTHING