? ? ? 最近在開發公眾號項目,每次公眾號發布新版本的時候,用戶打開的時候都是之前的舊版本,需要清除緩存之后才能用到新的版本,因此用戶體驗很不好,經常收到投訴.解決這個問題成了迫在眉睫的事情.? 通過各種途徑去搜索和查詢資料,終于找到解決的辦法.
解決方案如下:
一、index.html文件如何保證不緩存,每次都使用服務器上最新的代碼?
此時需要一下標簽:
<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" />
由于自定義了meta標簽想要實現自動化打包添加該標簽,需要添加自定義html模板
1.新建template.h5.html文件,代碼如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<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" />
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || CSS.supports('top: constant(a)'))
document.write('<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + (coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<link rel="stylesheet" href="<%= BASE_URL %>static/index.<%= VUE_APP_INDEX_CSS_HASH %>.css" />
</head>
<body>
<noscript>
<strong>Please enable JavaScript to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
2、 在manifest.json=>h5配置=>index.html模板路徑添加文件名稱? :? template.h5.html
添加此標簽后用戶每次請求的都是服務器是上最新版本的html文件,但是不能保證js文件都是最新的,因此還需要第二步
二、保證每次打包后的js文件名和之前的文件名字都不一樣,此時找不到文件名就會到服務器請求最新的文件,即可保安每次不會使用緩存文件,需要在vue.config.js文件添加以下代碼
let filePath = '';? // 默認文件路徑
let TimeStamp = '';? // 時間戳
let Version = '-V1.0.1-'; // 版本號
//編譯環境判斷,可以根據不同環境來做相應的配置
if (process.env.UNI_PLATFORM === 'h5') {
? filePath = 'static/js/'
? TimeStamp = new Date().getTime();
? process.env.VUE_APP_INDEX_CSS_HASH=`${Version}${TimeStamp}`? //給css文件也使用該時間戳
}
module.exports = {
? configureWebpack: {
? ? output: { //重構文件名
? ? ? filename: `${filePath}[name].${Version}${TimeStamp}.js`, // index文件重命名為帶有版本號+時間戳的格式
? ? ? chunkFilename: `${filePath}[name].${Version}${TimeStamp}.js` // static/js/pages-home-index.-V1-754654657.js?
? ? },
? },
}