解決 Vue 項目打包上線后客戶端緩存的問題


由於重新打包后會導致對應的 js 和 css 文件 hash 值發生變化,客戶端不刷新的話就會存在之前的文件找不到,導致報錯的問題。

 

通過 build.sh 定義打包命令

#!/usr/bin/env bash

# 更新當前時間戳
timestamp=`date '+%s'`
str="{ \"timestamp\": $timestamp }"
echo $str > "public/release.json"

# 根據需要寫 打包命令
# rm -rf dist
# rm -rf node_modules
# npm run build

 

每次上線前都會創建文件   <項目路徑>/public/release.json  例如:

{ "timestamp": 1639550254 }

是一個當前的時間戳。

 

然后設置一個全局的路由守衛

import axios from 'axios';
let timestamp;

const testRelease = () => {
    let url = `/release.json?t=${Date.now()}`;
    axios.get(url).then(res => {
        if (res.status === 200) {
            let lastTimestamp = timestamp;  // 上次時間戳
            timestamp = res.data.timestamp; // 當前時間戳
            if (lastTimestamp && lastTimestamp !== timestamp) { // 時間戳不相同的話就重新加載頁面
                window.location.reload();
            }
        }
    });
}

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [] // 根據業務定義路由
});

router.beforeEach(async function (to, from, next) {
    testRelease(); // 每次切換路由都調用接口測試時間戳是否更新
    next();
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM