最近碰到如题目所说的问题,用了思路一的解决方法,结束之后又上网看技术大牛们的解决方法,总结得出下面的文章。
方式一:纯前端
每次打包发版时都使用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 =<