清除文件缓存

1.index.html 文件添加 http-equiv(http 响应头)

通过在head标签中添加meta,当浏览器访问index.html时,会向服务器重新请求静态资源。该方法了解即可,不推荐使用,会导致用户每次访问程序都需要重新请求服务器,所有静态资源都无法使用缓存,浪费流量,网络压力大。

// 设定网页的到期时间,一旦网页过期,必须到服务器上重新传输。
<meta http-equiv="Expires" content="0">
// 设定禁止浏览器从本地机的缓存中调阅页面内容
<meta http-equiv="Pragma" content="no-cache">
// 清除缓存,再次访问这个网址要重新下载
<meta http-equiv="Cache-control" content="no-cache">

2.给打包的js、css文件添加时间戳

项目打包时给js、css文件加上时间戳,保证输出的文件名不会相同,通过 vue.config.js 进行配置。

// 获取当前时间戳
const timeStamp = new Date().getTime()
// 时间戳配置
module.exports = {
  // 打包后的文件输出路径
  outputDir: 'dist',
  configureWebpack: {
    // 输出重构 打包编译后的js文件名称,添加时间戳
    output: {
      filename: `js/[name].${timeStamp}.js`,
      chunkFilename: `js/[name].${timeStamp}.js`,
    }
  },
  css: {
    // 输出重构 打包编译后的css文件名称,添加时间戳
    extract: {
      filename: `css/[name].${timeStamp}.css`,
      chunkFilename: `css/[name].${timeStamp}.css`,
    }
  }
}

了解:
filename: 指列在 entry(入口) 中,打包后输出的文件的名称
chunkFilename: 指未列在 entry 中,却又需要被打包出来的文件的名称(懒加载的文件)

清除浏览器 localStorage 缓存

1、更新package.json中的 version 值,每次打包往上递增
2、main.js中,根据 version 判断是否进行缓存清理

const VUE_APP_VERSION = require('../package.json').version
const vers = window.localStorage.getItem('appVersion')
if(VUE_APP_VERSION != vers){
  localStorage.clear()
  window.localStorage.setItem('appVersion', VUE_APP_VERSION)
  location.reload()
}
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐