前端构建通知用户更新

35 阅读1分钟

一、webpack版本配置

1.修改vue.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const fs = require('fs');
const path = require('path');

const getAppVersion = () => {
  // 若想自定义语义化版本,可改为固定值,如 return 'v2.0.1',每次发版手动改
  return new Date().getTime().toString(); 
};
const APP_VERSION = getAppVersion();

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true,
      templateParameters: {
        appVersion: APP_VERSION
      }
    }),
    function() {
      this.plugin('done', (stats) => {
        const versionJsonPath = path.resolve(__dirname, '../dist/version.json');
        fs.writeFileSync(
          versionJsonPath,
          JSON.stringify({ version: APP_VERSION }, null, 2),
          'utf8'
        );
      });
    }
  ]
};
2. 修改项目根目录的 index.html(模板文件)
<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Vue 2 Webpack 项目</title>
    <!-- 注入版本变量,生成全局变量 -->
    <script>
      window.__APP_VERSION__ = '<%= appVersion %>'; 
    </script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
3.路由拦截配置
封装版本检测函数:请求 version.json 对比版本
const checkNewVersion = async () => {
  try {
    const response = await fetch('/version.json', {
      // 禁用缓存
      headers: { 'Cache-Control': 'no-cache' }
    });
    const { version: latestVersion } = await response.json();
    // 对比
    const localVersion = window.__APP_VERSION__;
    return localVersion !== latestVersion; // 返回 true 表示有更新
  } catch (error) {
    console.error('版本检测失败:', error);
    return false; // 失败时不提示,避免影响用户
  }
};

路由守卫

router.beforeEach(async (to, from, next) => {
  // 从一个页面跳转到另一个页面时检测
  if (from.name) {
    const hasNewVersion = await checkNewVersion();
    if (hasNewVersion) {
      // 提示用户更新
      const confirmUpdate = window.confirm('发现新功能更新,点击确定刷新生效~');
      if (confirmUpdate) {
        // 强制刷新页面
        window.location.reload(true);
        return;
      }
    }
  }
  // 无更新正常跳转
  next();
});