vue项目发版,缓存问题。

您所在的位置:网站首页 缓存的问题 vue项目发版,缓存问题。

vue项目发版,缓存问题。

2023-09-28 13:58| 来源: 网络整理| 查看: 265

在vue项目开发中,一直有一个令人都疼的问题,就是缓存问题;每次发版完之后由于浏览器缓存机制,用户端不会实时获取新的项目页面,甚至有可能出现静态文件获取报404,之前的解决方案是告知用户手动清理浏览器缓存,但是这种方式并不友好,因为用户未必知道怎么清理缓存,而且就算用户知道怎么清理缓存,也不清楚什么时候该清理。所以针对这种问题,推出了一种新的解决方案。

方案思路:

一. public/index.html配置meta,去掉缓存

二. 打包,在此过程中做了一下几件事情:

    1.生成一个随机版本号,并记录到env中

    2.在静态文件上添加时间戳

    3.生成一个记录版本号的静态文件public/config.json

三. 写一个version判断方法,在全局router.beforeEach中判断版本号是否有更新,如果有更新则提示用户刷新页面。

详细步骤如下:

1.在vue项目public文件夹下的index.html入口文件中添加如下代码

2.在vue.config.js中添加如下配置

const Timestamp = (new Date()).getTime() const gitRevisionPlugin = new GitRevisionPlugin() // 依赖 git-revision-webpack-plugin const VERSION = `${gitRevisionPlugin.branch()}_${gitRevisionPlugin.version()}_${gitRevisionPlugin.commithash()}_${Timestamp}` // git分支+时间戳;这里可以根据自己喜欢的方式加上随机版本号 process.env.VUE_APP_VERSION = VERSION // 记录到env,并在vuex中记录,用于后面版本号对比校验 const configJSON = require(resolve('public/config.json')) // public文件夹下新建config.json const configFile = path.resolve(__dirname, 'public/config.json') fs.writeFileSync(configFile, JSON.stringify({ ...configJSON, version: VERSION }, null, 2)) ... chainWebpack (config) { // 打包文件上添加时间戳 if (process.env.NODE_ENV === 'production') { config.output.filename(`static/js/[name].js?v=${Timestamp}`).end() config.output.chunkFilename(`static/js/[name].js?v=${Timestamp}`).end() config.plugin('extract-css').tap(() => [{ filename: `static/css/[name].css?v=${Timestamp}`, chunkFilename: `static/css/[name].css?v=${Timestamp}` }]).end() }

3.在utils下,新建systemUpdate.js

import axios from 'axios' import store from '@/store' import { removeLocalStorage, setLocalStorage } from '@/utils/localStorage' import { MessageBox } from '@/element-ui' const getConfig = () => { return new Promise((resolve) => { axios.get(`${process.env.VUE_APP_DOMAIN}/config.json`, { params: { _t: (new Date()).getTime() } }).then(res => { resolve(res.data) }) }) } export async function isNewVersion () { if (process.env.NODE_ENV === 'development') { return false } const config = await getConfig() let newVersion = config.version let oldVersion = store.getters.version let isUpdated = oldVersion !== newVersion if (isUpdated) { // 如果version不一致,则清除本地基础数据 removeLocalStorage('AREADATA') MessageBox.alert( '系统检测到有新版本,请刷新页面!', '系统提示', { showClose: false, confirmButtonText: '刷新页面' } ).then(() => { setLocalStorage('VERSION', { version: newVersion }) window.location.reload() }).catch(() => { }) } return isUpdated }

4.router.beforeEach中判断版本号

router.beforeEach(async (to, from, next) => { // 判断版本号,如果不一致则提示用户刷新页面 const isUpdate = await isNewVersion() if (isUpdate) return false ...

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3