前言:每次測試構(gòu)建或者打包更新版本發(fā)到服務(wù)器上,導(dǎo)致偶爾會(huì)出現(xiàn)不能及時(shí)更新到最新代碼,瀏覽器存在緩存的問題。
一、js、css文件防緩存
定義版本變量: const? Version = new Date().getTime(); // 這里使用的是時(shí)間戳 來區(qū)分 ,實(shí)際上不用加時(shí)間戳,webpack內(nèi)部還自動(dòng)變化hash值
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].'+_Version+'js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].'+_Version+'js')
}
二、html文件防緩存
方法1、Linux服務(wù)器設(shè)置nginx禁用html緩存
在開發(fā)調(diào)試web的時(shí)候,經(jīng)常會(huì)碰到因?yàn)g覽器緩存(cache)而經(jīng)常要去清空緩存或者強(qiáng)制刷新來測試的煩惱,提供下apache不緩存配置和nginx不緩存配置的設(shè)置。在常用的緩存設(shè)置里面有兩種方式,都是使用add_header來設(shè)置:分別為Cache-Control和Pragma。
add_header Cache-Control no-store;
add_header Pragma no-cache;
server {
listen 80;
server_name test.exmaple.cn;
location / {
if ($request_filename ~* .*\.(?:htm|html)$) ## 配置頁面不緩存html和htm結(jié)尾的文件
{
add_header Cache-Control "private, no-store, no-cache, must-revalidate, proxy-revalidate";
}
root /web/;
index index.html;
try_files $uri $uri/ /index.html =404;
}
}
?方法2、index.html頁面添加
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Cache" content="no-cache">
方法3、(Vue-cli前端代碼控制)
1.在public靜態(tài)目錄下新建version.json每次發(fā)版更改里面的版本號(hào)?
{
? ? "version": "0.0.1"
}
2.在src中新建 libs/versionUpdate.js文件文章來源:http://www.zghlxwxcb.cn/news/detail-479700.html
import axios from 'axios'
?
const isNewVersion = () => {
? let url = `//${window.location.host}/version.json?t=${new Date().getTime()}`
? axios.get(url).then(res => {
? ? if (res.status === 200) {
? ? ? let vueVersion = res.data.version || '1.0.0'
? ? ? let localVueVersion = localStorage.getItem('vueVersion')
? ? ? localStorage.setItem('vueVersion', vueVersion)
? ? ? if (localVueVersion && localVueVersion != vueVersion) {
? ? ? ? alert('檢測到新版本,請點(diǎn)擊確認(rèn)刷新頁面哦')
? ? ? ? window.location.reload(true)
? ? ? ? return
? ? ? }
? ? }
? })
}
?
export default {
? isNewVersion
}
3.在全局路由攔截中寫,只要每次版本號(hào)不同就重新加載頁面配合第一步就可以清楚瀏覽器緩存文章來源地址http://www.zghlxwxcb.cn/news/detail-479700.html
import versionTood from '@/libs/versionUpdate'
?
router.beforeEach(( to, from, next ) => {
? //判斷當(dāng)前代碼版本是否與服務(wù)器中代碼版本一致,如不一致則刷新頁面獲取最新
? versionTood.isNewVersion();
}
到了這里,關(guān)于vue項(xiàng)目發(fā)布有緩存,正式環(huán)境不更新(解決方案)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!