vue+electron 自动更新

1. 配置 package.json或vue.config.js文件中的应用更新服务器地址
javascript 复制代码
module.exports = {
  pluginOptions: {
    electronBuilder: {
        ...
        
        publish: [
          {
            provider: 'generic',
            url: 'http://qc***/***'  // 服务器地址
          }
        ]

        ...

      }
    }
  }
}
2. 在主进程写更新应用逻辑

checkupdate.js 文件或 main.js 中写入

javascript 复制代码
import { autoUpdater } from 'electron-updater'
const { build } = require("../../../package.json")
const { app, dialog } = require('electron');
const path = require("path");
import { ipcRenderer } from "electron";
const websocket = require('ws')

//跳过打包检查  开发环境使用  打包的时候注释掉
// Object.defineProperty(app, 'isPackaged', {
// 	get() {
// 		return true;
// 	}
// });
/**
 * -1 检查更新失败 0 正在检查更新 1 检测到新版本,准备下载 2 未检测到新版本 3 下载中 4 下载完成
 **/
class Update {
    mainWindow
    constructor() {
        autoUpdater.setFeedURL(build.publish[0].url)

        // 当更新发生错误的时候触发。
        autoUpdater.on('error', (err) => {
            if (err.message.includes('sha512 checksum mismatch')) {
                this.Message(this.mainWindow, -1, 'sha512校验失败')
            } else {
                this.Message(this.mainWindow, -1, '错误信息请看主进程控制台')
            }
        })

        // 当开始检查更新的时候触发
        autoUpdater.on('checking-for-update', (event, arg) => {
            this.timer(this.mainWindow, 0, "正在检查更新...", 5000)
        })

        // 发现可更新数据时
        autoUpdater.on('update-available', (event, arg) => {
            this.timer(this.mainWindow, 1, "发现新版本", 10000)
            this.timer(this.mainWindow, 1, "检测到新版本,正在下载安装包...", 15000)
        })

        // 没有可更新数据时
        autoUpdater.on('update-not-available', (event, arg) => {
            this.timer(this.mainWindow, 2, "暂未检测到新版本,当前版本为最新版本,无需更新", 15000)
        })

        // 下载监听  
        autoUpdater.on('download-progress', (progressObj) => {
            // {
            //   total: 1145589126,
            //   delta: 71139212,
            //   transferred: 71139212,
            //   percent: 6.209836527376395,
            //   bytesPerSecond: 69881348
            // }

            let total = this.renderSize(progressObj.total); //总大小
            let percent = parseFloat(progressObj.percent.toFixed(2)); //下载进度
            let bytesPerSecond = this.renderSize(progressObj.bytesPerSecond); //下载速度
            // let message = `总大小:${total} 下载进度:${percent}% 下载速度${bytesPerSecond}/S`
            let message = `总大小:${total} 下载进度:${percent}%`
            // this.Message(this.mainWindow, 3, message)
        })

        // 下载完成
        autoUpdater.on('update-downloaded', () => {
            // console.log('done')
            this.Message(this.mainWindow, 4, "新版本已下载完成,五秒后自动安装并重启...")
            setTimeout(() => {
                this.quitInstall();
            }, 5000)
        })
    }

    // 负责向渲染进程发送信息
    Message(mainWindow, type, data) {
        const senddata = {
            state: type,
            msg: data || ''
        }
        let journalSocket = new websocket("ws://localhost:16478");
        // mainWindow.webContents.send('update-msg', senddata)
        journalSocket.on("open", function () {
            journalSocket.send(data);
        });
    }

    // 执行自动更新检查
    checkUpdate(mainWindow) {
        this.mainWindow = mainWindow
        autoUpdater.updateConfigPath = path.resolve(__static, 'default-app-update.yml')
        // this.Message(this.mainWindow, 4, path.resolve(__static, 'default-app-update.yml'))
        // autoUpdater.currentVersion = "0.0.1";//调试使用 正式上线后注释掉
        autoUpdater.checkForUpdates().catch(err => {
            console.log('网络连接问题', err)
        })
    }

    // 退出并安装
    quitInstall() {
        autoUpdater.quitAndInstall()
    }

    // 处理文件大小格式化
    renderSize(value) {
        if (null == value || value == '') {
            return "0 Bytes";
        }
        var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
        var index = 0;
        var srcsize = parseFloat(value);
        index = Math.floor(Math.log(srcsize) / Math.log(1024));
        var size = srcsize / Math.pow(1024, index);
        size = size.toFixed(2);//保留的小数位数
        return size + unitArr[index];
    }

    // 定时器
    timer(mainWindow, number, message, time) {
        setTimeout(() => {
            this.Message(mainWindow, number, message)
        }, time)
    }
}


export default Update

3. 打包升级版的应用(v1.1.0)

注意:

每次打包记得去package.json文件中修改version版本号,这样系统才会检测到最新版本

打包后 dis有如下两个文件:

新版本安装包.exe

latest.yml

将上面两个文件复制到 '更新服务器' (http://qc***/***) 目录下;

以后每次有更新就复制这两个文件至 '更新服务器',旧版本的应用的执行文件(.exe)可以删除。

相关推荐
胡萝卜术6 分钟前
力扣5. 最长回文子串
前端·javascript·面试
我星期八休息24 分钟前
网络编程—应用层HTTP协议
linux·运维·开发语言·前端·网络·网络协议·http
不好听6131 小时前
前端路由完全指南(下篇):懒加载、History 栈与工程化实践
前端·react.js
圣光SG3 小时前
Java Web入门基础知识笔记
java·前端·笔记
cyforkk4 小时前
Vercel 绑定自定义域名极简配置指南
服务器·前端·网络
IT_陈寒5 小时前
React useEffect依赖数组中埋的坑,这次终于让我逮到了
前端·人工智能·后端
FourAu6 小时前
2026 前端突围指南:从 ESR 边缘渲染到封装 Web AI SDK,聊聊 AI 时代的职业进化
前端·人工智能
Zkeq6 小时前
不止是聊天框:我用 EdgeOne Makers Agents 给烹饪 APP 加了一位能“改菜谱”的 AI 主厨
前端
咩咩啃树皮6 小时前
第32篇:前端本地存储全解——Cookie、localStorage、sessionStorage 区别与实战
前端