• web应用及微信小程序版本更新检测方案实践


    背景:

    随着项目体量越来越大,用户群体越来越多,用户的声音也越来越明显;关于应用发版之后用户无感知,导致用户用的是仍然还是老版本功能,除非用户手动刷新,否则体验不到最新的功能;这样的体验非常不好,于是我们团队针对该问题给出了相应的解决方案来处理;

    技术栈:vue3+ts+vite+ant-design-vue

    1. web应用版本检测方案:

    1. 基于vite开发自定义插件version-update,vite打包流程运行version-update插件在项目结构目录public文件夹下生成version.json文件,通过读取version.json文件内容与服务器上的资源文件作为版本更新的比对依据
     /** src/plugin/versionUpdate.ts  **/
     import fs from 'fs'
     import path from 'path'
     interface OptionVersion {
       version: number | string
     }
     interface configObj extends Object {
       publicDir: string
     }
     
     const writeVersion = (versionFileName: string, content: string | NodeJS.ArrayBufferView) => {
       // 写入文件
       fs.writeFile(versionFileName, content, (err) => {
         if (err) throw err
       })
     }
     
     export default (options: OptionVersion) => {
       let config: configObj = { publicDir: '' }
       return {
         name: 'version-update',
         configResolved(resolvedConfig: configObj) {
           // 存储最终解析的配置
           config = resolvedConfig
         },
     
         buildStart() {
           // 生成版本信息文件路径
           const file = config.publicDir + path.sep + 'version.json'
           // 这里使用编译时间作为版本信息
           const content = JSON.stringify({ version: options.version })
           /** 判断目录是否存在 */
           if (fs.existsSync(config.publicDir)) {
             writeVersion(file, content)
           } else {
             /** 创建目录 */
             fs.mkdir(config.publicDir, (err) => {
               if (err) throw err
               writeVersion(file, content)
             })
           }
         }
       }
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    1. 将该文件作为插件放入到vite的plugin中去执行,并在vite构建过程中声明一个全局变量process.env.VITE__APP_VERSION__(这里仅仅只是一个变量,只用来记录打包时间和服务器json内容对比),值为当前时间戳
     /** vite.config.ts  **/
     import { defineConfig } from 'vite'
     import vue from '@vitejs/plugin-vue'
     import vueJsx from '@vitejs/plugin-vue-jsx'
     import VueSetupExtend from 'vite-plugin-vue-setup-extend'
     import { visualizer } from 'rollup-plugin-visualizer'
     import viteCompression from 'vite-plugin-compression'
     import versionUpdatePlugin from './src/plugins/versionUpdate' //Rollup 的虚拟模块
     // vite.config.ts
     import type { ViteSentryPluginOptions } from 'vite-plugin-sentry'
     import viteSentry from 'vite-plugin-sentry'
     // @ts-ignore
     const path = require('path')
     
     const NODE_ENV = process.env.NODE_ENV
     const IS_PROD = NODE_ENV === 'production'
     const CurrentTimeVersion = new Date().getTime()
     /*
       Configure sentry plugin
     */
     const sentryConfig: ViteSentryPluginOptions = {
       url: 'https://sentry.jtexpress.com.cn',
       authToken: '85ceca5d01ba46b2b6e92238486250d04329713adf5b4ef68a8e094102a4b6e1',
       org: 'yl-application',
       project: 'post-station',
       release: process.env.npm_package_version,
       deploy: {
         env: 'production'
       },
       setCommits: {
         auto: true
       },
       sourceMaps: {
         include: ['./dist/static/js'],
         ignore: ['node_modules'],
         urlPrefix: '~/static/js'
       }
     }
     
     // https://vitejs.dev/config/
     export default defineConfig({
       define: {
         // 定义全局变量
         'process.env.VITE__APP_VERSION__': CurrentTimeVersion
       },
       plugins: [
         IS_PROD && versionUpdatePlugin({
           version: CurrentTimeVersion
         }),
         vueJsx(),
         vue(),
         VueSetupExtend(),
         visualizer(),
         // gzip压缩 生产环境生成 .gz 文件
         viteCompression({
           verbose: true,
           disable: false,
           threshold: 10240,
           algorithm: 'gzip',
           ext: '.gz'
         }),
         IS_PROD && viteSentry(sentryConfig)
       ],
       resolve: {
         alias: {
           // @ts-ignore
           '@': path.resolve(__dirname, 'src')
         }
       },
       css: {
         preprocessorOptions: {
           less: {
             modifyVars: {
               // antd 自定义主题 https://www.antdv.com/docs/vue/customize-theme-cn
               'primary-color': '#1890ff',
               'link-color': '#1890ff',
               'border-radius-base': '2px'
             },
             additionalData: '@import "@/assets/style/common.less";',
             javascriptEnabled: true
           }
         }
       },
       server: {
         host: '0.0.0.0',
         port: 8080,
         open: false,
         https: false,
         proxy: {}
       },
       build: {
         minify: 'terser',
         terserOptions: {
           compress: {
             /* 清除console */
             drop_console: true,
             /* 清除debugger */
             drop_debugger: true
           }
         },
         rollupOptions: {
           output: {
             chunkFileNames: 'static/js/[name]-[hash].js',
             entryFileNames: 'static/js/[name]-[hash].js',
             assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
             manualChunks(id) {
               //静态资源分拆打包
               if (id.includes('node_modules')) {
                 return id.toString().split('node_modules/')[1].split('/')[0].toString()
               }
             }
           }
         },
         sourcemap: IS_PROD
       }
     })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    1. 封装全局方法,请求当前域名下的/version.json资源,将vite中定义的全局变量和当前域名下的json文件内容做对比,如果不一致,我们则认为发布了新版本
    /** src/utils/checkVersion.ts **/
    import { Modal } from 'ant-design-vue'
    export default function versionCheck() {
      const timestamp = new Date().getTime()
      //import.meta.env.MODE 获取的是开发还是生产版本的
      if (import.meta.env.MODE === 'development') return
    
      fetch(`/version.json?t=${timestamp}`)
        .then((res) => {
           return res.json()
         })
         .then((response) => {
           if (process.env.VITE__APP_VERSION__ !== response.version) {
             Modal.confirm({
               title: '发现新版本',
               content: '检测到最新版本,刷新后立即使用...',
               okText: '立即更新',
               cancelText: '暂不更新',
               onOk() {
                 window.location.reload()
               }
             })
           }
         })
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    1. 在layout全局文件中,监听路由变化,去调版本检测的方法来决定是否弹出提醒(尊重用户的选择,是否更新页面由用户来决定)
     /** src/layout/index.vue **/
      watch(
         () => router.currentRoute.value,
         (newValue: any) => {
           /** 判断是否有更高的版本 */
           checkVersion()
         },
         { immediate: true }
       )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2、微信小程序应用版本检测方案:

    流程图:

    小程序版本更新流程图

    技术栈:Taro-vue+ts+nut-ui (京东物流风格轻量移动端组件库)

    1. 基于微信开发文档提供的getUpdateManager版本更新管理器api去实现版本更新的检测与新版本应用的下载,封装全局方法)
     1 /** 检查小程序版本更新 */
     2 export function checkMiniProgramVersion() {
     3   if (Taro.canIUse('getUpdateManager')) {
     4     const updateManager = Taro.getUpdateManager();
     5     updateManager.onCheckForUpdate(function (res) {
     6       // 请求完新版本信息的回调
     7       if (res.hasUpdate) {
     8         Taro.showModal({
     9           title: '新版本更新提示',
    10           content: '检测到新版本,是否下载新版本并重启小程序?',
    11           success: function (res) {
    12             if (res.confirm) {
    13               downloadAndUpdate(updateManager);
    14             }
    15           },
    16         });
    17       }
    18     });
    19   } else {
    20     Taro.showModal({
    21       title: '新版本更新提示',
    22       showCancel: false,
    23       content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。',
    24       success: function () {
    25         Taro.exitMiniProgram();
    26       },
    27     });
    28   }
    29 }
    30 
    31 /** 新版本应用下载 */
    32 export function downloadAndUpdate(updateManager) {
    33   Taro.showLoading();
    34   updateManager.onUpdateReady(function () {
    35     Taro.hideLoading();
    36     Taro.showModal({
    37       title: '新版本更新提示',
    38       content: '新版本已经准备好,是否重启应用?',
    39       success: function (res) {
    40         if (res.confirm) {
    41           // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
    42           updateManager.applyUpdate();
    43         }
    44       },
    45     });
    46   });
    47 
    48   updateManager.onUpdateFailed(function () {
    49     Taro.showLoading();
    50     Taro.showModal({
    51       title: '新版本更新提示',
    52       showCancel: false,
    53       content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~',
    54       success: function () {
    55         // 退出应用
    56         Taro.exitMiniProgram();
    57       },
    58     });
    59   });
    60 }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    1. 在app.ts入口文件onLaunch的生命周期钩子函数中去调用方法检测版本
    // src/app.ts
    import { createApp } from 'vue';
    import Taro from '@tarojs/taro';
    import './app.scss';
    import store from './store';
    import installPlugin from '@/plugins/index';
    import { wxLogin, checkMiniProgramVersion } from '@/utils/common';
    
    const App = createApp({
       onLaunch() {
         /** 检测小程序版本 */
         checkMiniProgramVersion();
       },
     });
     
     App.use(store);
     installPlugin(App);
     
     export default App;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    坑点Tips:

    小程序更新方案中由于受限于小程序的更新机制,第一次发版无效,因为微信小程序服务器上的版本中不存在checkMiniProgramVersion方法,所以无法执行;更新提示弹窗需要在第二次发版时才生效;

  • 相关阅读:
    第三章 ArcGIS Pro创建 python 脚本工具(二)
    Vue笔记:基础入门(前篇)
    怎么能还不会2PC、3PC?赶快学起来
    海外代理高性价比推荐——精选list
    自定义注解结合SpringAop实现权限,参数校验,日志等等功能
    扩展欧几里得
    万万没想到有一天居然可以在 Mac 上玩游戏,而且还是原神!
    windows的ui自动化测试相关
    C#.Net筑基-基础知识
    面试官:说说TCP如何实现可靠传输
  • 原文地址:https://blog.csdn.net/dengyao46395665/article/details/132943549