electron自动更新

最终效果

在开始之前, 先让我们看一下最终效果: 在打开软件的时候, 会自动判断当前是否为最新版(和文件服务器上的最新版本进行对比), 如果不是最新版, 则会自动下载安装并打开新版

自动更新过程.gif



在看过最终自动检测更新的效果之后, 让我们从头开始配置

初始化vue-cli3项目

vue-cli3初始化项目已经去掉了vue.config.js, 这里需要自己新增文件进行配置

安装与配置electron-updater

//安装
npm install electron-updater --save
  • 安装好后, 会在package.json中生成一些script脚本, 另外electron-builder的配置项需要写在vue.config.js中, 因为vue-cli3.0已不再支持package.json中配置config和build, 否则会报下述错误*
error: 'build' in the application package.json is not supported since 3.0 anymore

打开vue.config.js

pluginOptions:{
    ...
    electronBuilder: {
      nodeIntegration: true,
      contextIsolation: false,
      builderOptions: {
        productName: "vue-config-package",
        appId: "123",
        //注意, 只有在配置了publish路径时, build之后才会生成latest.yml文件
        publish: [
          {
            "provider": "generic",
            "url": "http://127.0.0.1:8000/"
          }
        ]
      }
    }
}

搭建文件服务器

在本地搭建文件服务器, 用于存放最新的安装包和latest.yml文件

  • latest.yml文件是自动更新的重要依据, 里面记录了版本号, 安装exe路径, 打包release时间等
npm i -g simplehttpserver
//进入根目录, 执行下列代码
simplehttpserver
//默认8000端口, 也可以自定义端口:  simplehttpserver -p 8080



前期准备和安装工作已经完成, 接下来要编写update.js脚本(主进程), 以及渲染页面中的监听和后续操作

主进程update.js

在background.js同级目录新增update.js, 用于封装主进程的electron-update的事件回调

import {
    autoUpdater
} from 'electron-updater'
 
import {
    ipcMain
} from 'electron'
let mainWindow = null;
export function updateHandle(window, feedUrl) {
    debugger
    mainWindow = window;
    let message = {
        error: '检查更新出错',
        checking: '正在检查更新……',
        updateAva: '检测到新版本,正在下载……',
        updateNotAva: '现在使用的就是最新版本,不用更新',
    };
    //设置更新包的地址
    autoUpdater.setFeedURL(feedUrl);
    //监听升级失败事件
    autoUpdater.on('error', function (error) {
        sendUpdateMessage({
            cmd: 'error',
            message: error
        })
    });
    //监听开始检测更新事件
    autoUpdater.on('checking-for-update', function (message) {
        sendUpdateMessage({
            cmd: 'checking-for-update',
            message: message
        })
    });
    //监听发现可用更新事件
    autoUpdater.on('update-available', function (message) {
        sendUpdateMessage({
            cmd: 'update-available',
            message: message
        })
    });
    //监听没有可用更新事件
    autoUpdater.on('update-not-available', function (message) {
        sendUpdateMessage({
            cmd: 'update-not-available',
            message: message
        })
    });
 
    // 更新下载进度事件
    autoUpdater.on('download-progress', function (progressObj) {
        sendUpdateMessage({
            cmd: 'download-progress',
            message: progressObj
        })
    });
    //监听下载完成事件
    autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl) {
        sendUpdateMessage({
            cmd: 'update-downloaded',
            message: {
                releaseNotes,
                releaseName,
                releaseDate,
                updateUrl
            }
        })
        //退出并安装更新包
        autoUpdater.quitAndInstall();
    });
 
    //接收渲染进程消息,开始检查更新
    ipcMain.on("checkForUpdate", (e, arg) => {
        //执行自动更新检查
        // sendUpdateMessage({cmd:'checkForUpdate',message:arg})
        autoUpdater.checkForUpdates();
    })
}
//给渲染进程发送消息
function sendUpdateMessage(text) {
    mainWindow.webContents.send('message', text)
}

background.js中:

//自动更新脚本
import { updateHandle } from './update.js';

async function createWindow() {
  ...
  //这里是文件服务器的根路径地址
  let feedUrl = "http://127.0.0.1:8000/";
  updateHandle(win,feedUrl);
}

渲染进程

App.vue

<template>
  <div>
      <p>当前版本1.0</p>
      <p v-if="dialogVisible">正在更新新版本,请稍候...</p>
  </div>
</tempalte>
<script>
let ipcRenderer = require("electron").ipcRenderer;
let _this = this;

//接收主进程版本更新消息
ipcRenderer.on("message", (event, arg) => {
  // for (var i = 0; i < arg.length; i++) {
  console.log('Appvue:',arg);
  if ("update-available" == arg.cmd) {
    //显示升级对话框
    _this.dialogVisible = true;
  } else if ("download-progress" == arg.cmd) {
    //更新升级进度
    console.log(arg.message.percent);
    let percent = Math.round(parseFloat(arg.message.percent));
    _this.percentage = percent;
  } else if ("error" == arg.cmd) {
    _this.dialogVisible = false;
    alert("更新失败");
  }
  // }
});
//2秒后开始检测新版本
let timeOut = window.setTimeout(() => {
  ipcRenderer.send("checkForUpdate");
}, 2000);
clearTimeout;
//间隔1分钟检测一次
let interval = window.setInterval(() => {
  ipcRenderer.send("checkForUpdate");
}, 60000);

export default {
  data(){
    return{
      dialogVisible: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      showClose: false,
      percentage: 0,
      strokeWidth:200
    }
  },
  mounted(){
    _this = this;
  },
  methods:{
    ipcRenderer(keyword){
      this.$electron.ipcRenderer.send(keyword,"123");
    },
  },
  destroyed() {
    window.clearInterval(interval);
    window.clearInterval(timeOut);
  }
}
</script>

测试步骤

  1. 更改package.json中的version和App.vue中任意内容(例如当前版本X.X可以看出当前版本效果特性的内容)
  2. 将最新的安装包放到simplehttpserver运行的本地文件服务根目录中
  3. 安装运行旧版本的包, 则会进入并且自动更新下载打开新的资源包





参考文档
1.electron官方文档:https://www.electronjs.org/docs/tutorial/quick-start
2.electron-builder官方文档:https://www.electron.build/api/electron-builder
3.electron-builder常用配置中文注释https://blog.csdn.net/sw7662504/article/details/109241935?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-8&spm=1001.2101.3001.4242
4.vue-cli2.0+electron配置教程https://blog.csdn.net/gsj4719896/article/details/100131840

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容