這個問題產品經理很早就提需求了,之前是通過修改webpack的打包的js文件規則解決的。但最近谷歌瀏覽器更新版本后,這個方法失效了,應該是瀏覽器默認緩存文件了。最后上網找了這個方法解決的。
方案一:用戶手動改瀏覽器配置
按F12或者右鍵->檢查,勾上disable cache,這個選項是禁用緩存。
方案二:通過代碼解決
這個方案第一次更新版本的時候需要清除緩存,但之后更新版本只需要刷新頁面就可以獲取最新的頁面代碼了。
1、用webpack打包js文件時,文件名增加一個時間戳,修改 webpack .prod.conf.js
文件
1 const version = new Date().getTime(); 2 output: { 3 path: config.build.assetsRoot, 4 filename: utils.assetsPath('js/[name].[chunkhash:8].' + version + '.js'), 5 chunkFilename: utils.assetsPath('js/[name].[chunkhash:8].' + version + '.js') 6 }
2、在 index.html 頁面前面加 meta 標簽,注意:記得加上,我就是忘記加上了,一直測試不過。
1 <meta http-equiv="pragram" content="no-cache">
2 <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
3 <meta name="viewport" content="width=device-width,initial-scale=1.0">
3、html 頁面加載腳本的時候給腳本后面加一個時間戳,修改 webpack.prod.conf.js
文件。
1 new HtmlWebpackPlugin({ 2 filename: config.build.index, 3 template: 'index.html', 4 inject: true, 5 hash: version, 6 minify: { 7 removeComments: true, 8 collapseWhitespace: true, 9 removeAttributeQuotes: true
10 },CommonsChunkPlugin 11 chunksSortMode: 'dependency'
12 }),
擴展:
vue-cli 里的默認配置,css 和 js 的名字都加了哈希值,所以新版本 css、js 和就舊版本的名字是不同的,不會有緩存問題。但是 index.html 放到服務器里去的時候,index.html 在服務器端可能是有緩存的,這需要在服務器配置不讓緩存 index.html。
4、修改 /conf/nginx.conf 配置文件,讓index.html不緩存,同時記得重啟nginx,直接用下面配置可以成功。
1 location /{
2 add_header Cache-Control no-cache; 3 }
參考網頁:https://blog.csdn.net/LonewoIf/article/details/89388843