美文网首页
2021-07-21 vue-cli3打包后清除浏览器缓存

2021-07-21 vue-cli3打包后清除浏览器缓存

作者: 追寻1989 | 来源:发表于2021-07-21 16:21 被阅读0次

该篇的做法已不推荐,仅供参考:请移步至更详细的文章【http常用缓存策略及vue-cli单页面应用、服务器端(nginx)如何设置缓存或者禁用】:https://www.jianshu.com/p/d09431a5fe53

1. 在index.html页面head中添加

如何完美滴使浏览器访问一个 HTML 页面时禁用缓存?
在测试某个 SPA 项目时,发现更改后 Chrome 浏览器页面刷新还是使用之前的版本。经调查发现 Chrome 默认缓存值为 300 秒。

经测试跨浏览器禁止缓存的 headers 如下:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
Cache-Control is for HTTP 1.1
Pragma is for HTTP 1.0
Expires is for proxies

因为是 HTML 页面,可以于 HEAD 标签内直接添加 META 标签:

<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" />

其他文件就需要使用服务器设置文件控制 header

如果不想彻底禁止缓存可以采用下面的

<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="expires" content="0" />

no-cache和no-store的区别:
no-cache 可以在本地缓存,可以在代理服务器缓存,但是这个缓存要服务器验证才可以使用
no-store 彻底得禁用缓冲,本地和代理服务器都不缓冲,每次都从服务器获取

 <meta http-equiv="pragram" content="no-cache" />
 <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate"  />
 <meta http-equiv="expires" content="0" />
2. 创建vue.config.js文件,在打包文件名中添加时间戳

a、创建时间戳

const Timestamp = new Date().getTime();

b、在打包文件名中添加.时间戳或hash值

若添加时间戳(相对于上一次打包文件名全部文件名称都会改变,将导致全部文件都更新)

configureWebpack: {
   output: { // 输出重构  打包编译后的 文件名称  【模块名称.时间戳】防止发版文件缓存
     filename: `[name].${Timestamp}.js`,
     chunkFilename: `[name].${Timestamp}.js`
   },
 },

若添加时间戳(相对于上一次打包文件名只改变变动过的文件名,只导致局部文件更新,更能优化网站加载速度)

configureWebpack: {
    output: { // 输出重构  打包编译后的 文件名称  【模块名称.时间戳】 防止发版文件缓存
      filename: `[name].[hash:8].js`,
      chunkFilename: `[name].[hash:8].js`
    },
 },

相关文章

网友评论

      本文标题:2021-07-21 vue-cli3打包后清除浏览器缓存

      本文链接:https://www.haomeiwen.com/subject/tdmjmltx.html