当前位置: 首页 > news >正文

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

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

方式一:纯前端
每次打包发版时都使用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()
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • MFC常见问题解决
  • 3个方法教你如果快速绕过Excel工作表保护密码
  • 【ARM 常见汇编指令学习 7.1 -- LDRH 半字读取指令】
  • 时间处理的未来:Java 8全新日期与时间API完全解析
  • 串口工具推荐
  • stm32按键设置闹钟数进退位不正常?如何解决
  • 图文讲解IDEA如何导入JDBC驱动包
  • 【效率提升】多功能组织和整理软件一Notion
  • 【算法:贪心】:贪心算法介绍+基础题(四个步骤);柠檬水找零(交换论证法)
  • 第一个vue——01
  • Flutter——最详细(Table)网格、表格组件使用教程
  • 查看oracle ojdbc所支持的JDBC驱动版本
  • 大数据面试题之Greenplum(2)
  • Qt触发paintEvent事件
  • ✅小程序申请+备案教程
  • 网络传输文件的问题
  • Angular js 常用指令ng-if、ng-class、ng-option、ng-value、ng-click是如何使用的?
  • Java 9 被无情抛弃,Java 8 直接升级到 Java 10!!
  • Java比较器对数组,集合排序
  • Shell编程
  • spring boot 整合mybatis 无法输出sql的问题
  • UEditor初始化失败(实例已存在,但视图未渲染出来,单页化)
  • windows下使用nginx调试简介
  • 海量大数据大屏分析展示一步到位:DataWorks数据服务+MaxCompute Lightning对接DataV最佳实践...
  • 区块链将重新定义世界
  • 在Unity中实现一个简单的消息管理器
  • 策略 : 一文教你成为人工智能(AI)领域专家
  • ​1:1公有云能力整体输出,腾讯云“七剑”下云端
  • ​浅谈 Linux 中的 core dump 分析方法
  • #C++ 智能指针 std::unique_ptr 、std::shared_ptr 和 std::weak_ptr
  • #Linux(make工具和makefile文件以及makefile语法)
  • #Z2294. 打印树的直径
  • #我与Java虚拟机的故事#连载07:我放弃了对JVM的进一步学习
  • ()、[]、{}、(())、[[]]命令替换
  • (4) openssl rsa/pkey(查看私钥、从私钥中提取公钥、查看公钥)
  • (M)unity2D敌人的创建、人物属性设置,遇敌掉血
  • (附源码)springboot家庭装修管理系统 毕业设计 613205
  • (个人笔记质量不佳)SQL 左连接、右连接、内连接的区别
  • (九)One-Wire总线-DS18B20
  • (南京观海微电子)——I3C协议介绍
  • (三)模仿学习-Action数据的模仿
  • (微服务实战)预付卡平台支付交易系统卡充值业务流程设计
  • (转载)从 Java 代码到 Java 堆
  • .360、.halo勒索病毒的最新威胁:如何恢复您的数据?
  • .NET CLR基本术语
  • .NET Remoting Basic(10)-创建不同宿主的客户端与服务器端
  • .net 使用ajax控件后如何调用前端脚本
  • .NET 事件模型教程(二)
  • .NET/MSBuild 中的发布路径在哪里呢?如何在扩展编译的时候修改发布路径中的文件呢?
  • .NET和.COM和.CN域名区别
  • .NET设计模式(7):创建型模式专题总结(Creational Pattern)
  • .net图片验证码生成、点击刷新及验证输入是否正确
  • .NET中两种OCR方式对比
  • @ModelAttribute使用详解
  • [12] 使用 CUDA 加速排序算法