前端发布项目后,解决缓存的老版本文件问题

最近碰到如题目所说的问题,用了思路一的解决方法,结束之后又上网看技术大牛们的解决方法,总结得出下面的文章。

方式一:纯前端
每次打包发版时都使用webpack构建一个version.json文件,文件里的内容是一个随机的字符串(我用的是时间戳),每次打包都会自动更新这个文件。
项目中,通过监听点击事件来请求version.json文件。使用本地缓存将上一次生成的字符串存储起来,和本次请求过来的字符串进行对比;若字符串不一样,则说明有项目有新内容更新,提供用户刷新或清除缓存

方式二:前后端配合
在每个请求头加上发版的版本号,和保留在客户端的上一次版本号进行对比,如果不一致则强制刷新,刷新后保存当前版本号
实现:
1、webpack构建生成一个json文件,在项目目录下新建一个plugins的文件夹,新建version-webpack-plugin.js文件
webpack4****等高版本构建方式

/** Customized plug-in: Generate version number json file */const fs = require("fs");class VersionPlugin {  apply(compiler) {    // emit is an asynchronous hook, use tapAsync to touch it, you can also use tapPromise/tap (synchronous)    compiler.hooks.emit.tap("Version Plugin", (compilation) => {      const outputPath = compiler.path || compilation.options.output.path;      const versionFile = outputPath + "/version.json";      const timestamp = Date.now(); // timestamp as version number      const content = `{"version": "${timestamp}"}`;      /** Returns true if the path exists, false otherwise */      if (!fs.existsSync(outputPath)) {        // Create directories synchronously. Returns undefined or the path to the first directory created if recursive is true. This is the synchronous version of fs.mkdir().        fs.mkdirSync(outputPath, { recursive: true });      }      // Generate json file      fs.writeFileSync(versionFile, content, {        encoding: "utf8",        flag: "w",      });    });  }}module.exports = { VersionPlugin };

webpack3低版本构建方式

/** Customized plug-in: Generate version number json file */const fs = require('fs')class VersionPlugin {  apply(compiler) {    compiler.plugin('done', function () {      // Copy the logic of the file, and the file has been compiled.      const outputPath = compiler.outputPath      const versionFile = outputPath + '/version.json'      const timestamp = Date.now() // 时间戳作为版本号      const content = `{"version": "${timestamp}"}`      /** Returns true if the path exists, false otherwise. */      if (!fs.existsSync(outputPath)) {        // Create directories synchronously. Returns undefined or the path to the first directory created if recursive is true. This is the synchronous version of fs.mkdir().        fs.mkdirSync(outputPath, { recursive: true })      }      // Generate json file      fs.writeFileSync(versionFile, content, {        encoding: 'utf8',        flag: 'w'      })    })  }}module.exports = { VersionPlugin }

2、在vue.config.js中使用这个plugin

const { VersionPlugin } = require('./src/plugin/version-webpack-plugin')

config.plugins.push(new VersionPlugin())

在这里插入图片描述
3、在每次执行webpack构建命令,都会在dist目录下生成一个version.json文件,里面有一个字段叫version,值是构建时的时间戳,每次构建都会生成一个新的时间戳。
在这里插入图片描述
在这里插入图片描述
4、发起ajax请求,请求version.json文件获取version时间戳,和本地保存的上一次的时间戳做比较,如果不一样,则进行对应的操作。/business/version.json,business是我项目的前缀,改成你自己的项目地址,能请求到version.json文件就行。

import axios from 'axios'
import i18n from '@/i18n'
import UpdateMessage from '@/components/common/UpdateProject/index.js'
export function reloadVersion() {  
axios.get(window.location.origin + '/mobile/version.json?v=' + Date.now()).then(rsp => {    
let mobileVersion = localStorage.getItem('mobileVersion')   
let onlineVersion = rsp.data.version    
if (!mobileVersion) {      
localStorage.setItem('mobileVersion', onlineVersion)  return }    
if (onlineVersion) {      
if (mobileVersion !== onlineVersion) {        
UpdateMessage.success({          
title: i18n.t('bulk.pleaseWait'),          
msg: i18n.t('common.updateRemind')        
})        
setTimeout(() => {          
UpdateMessage.close()          
localStorage.setItem('mobileVersion', onlineVersion)          
window.location.reload();        
}, 2000);      
}    
}  
})}

5、请求发起的时机,可以使用定时器或者在切换页面的时候进行校验版本。根据自己的实际情况选择合适的调用时机。

async mounted() {  
process.env.NODE_ENV !== 'development' && window.addEventListener('mousedown', this.handleonmousedown);},
beforeDestroy() { 
 window.removeEventListener('mousedown', this.handleonmousedown)},
handleonmousedown() {   
reloadVersion()
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 17:52:03       99 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 17:52:03       107 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 17:52:03       90 阅读
  4. Python语言-面向对象

    2024-07-10 17:52:03       98 阅读

热门阅读

  1. Object.defineProperty与Proxy对比【简单易懂】

    2024-07-10 17:52:03       31 阅读
  2. docker安装tomcat容器

    2024-07-10 17:52:03       22 阅读
  3. 线段树动态开点

    2024-07-10 17:52:03       26 阅读
  4. 代码随想录算法训练营:29/60

    2024-07-10 17:52:03       25 阅读
  5. Postman接口测试工具详解

    2024-07-10 17:52:03       24 阅读
  6. 逻辑回归的损失函数

    2024-07-10 17:52:03       25 阅读
  7. postman接口测试工具详解

    2024-07-10 17:52:03       27 阅读
  8. SQL语法(DQL):SELECT 多表查询之子查询

    2024-07-10 17:52:03       30 阅读
  9. 获取和设置Spring Cookie

    2024-07-10 17:52:03       26 阅读
  10. Spring——配置说明

    2024-07-10 17:52:03       26 阅读
  11. springboot中在filter中用threadlocal存放用户身份信息

    2024-07-10 17:52:03       32 阅读