[Single page] How to [notify the client to update] after release
Symptom:
首先技术栈,是vue全家桶技术栈。典型spa单页应用,每次有新功能的上线,都需要主动通知,使用者自主刷新页面【强刷】,才能出现新功能。
cause:
Every time the package is released [the code changes], index.html, the entry file of the website is changed.
However, in a single-page application, the page jumps are all in the same browser thread, and the index.html resource will not be requested again, even if you do not cache the index.html resource, that is, set the response header information to cache-control : No-store is also not easy to use. The user has to refresh.
So what is the solution strategy, a picture is worth a thousand words:
- Introduce how to implement the plug-in in webpack [version 4]
// 获取并注入版本号 未写点【这里还可以写 把版本号 和 项目 名 发送到服务器,作版本记录】
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = class WebpackVersionPlugin {
constructor(options = { }) {
this.options = Object.assign({
versionName: '$AppVersion'
}, options)
}
apply(complier) {
const { versionName } = this.options;
complier.hooks.emit.tapAsync('WebpackVersionPlugin', (compilation, callback) => {
const { hash } = compilation
// 需要在 index.html 注入变量 【在htmlWebpackPlugin 钩子里处理 详细看官方文档】 HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
'MyPlugin',
(data, cb) => {
const htmlScriptStr = `<script>window.${versionName}="${hash}"</script>`
// 插入到第一个 script标签前面
data.html = data.html.replace(/(<script)/, `${htmlScriptStr}$1`)
cb(null, data)
}
)
callback()
})
}
}
The effect is as follows:
2 Why use location.reoload? By comparing the hash version of the rotation training, you can notify the user whether to refresh the page [ui level], if yes, call reload, otherwise no operation
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。