美文网首页
配置electron应用自动更新

配置electron应用自动更新

作者: shuaiutopia | 来源:发表于2021-03-05 14:35 被阅读0次

    本文介绍了 electron 开发桌面端应用的自动更新升级版本的方法, 以及更新服务器的搭建. electron项目搭建使用 vue-cli-plugin-electron-builder,自动更新使用的是 electron-updater, 它与electron-builder搭配使用.

    下文 background.ts 文件中还涉及了连接串口的使用方法, 当作笔记, 故未删除.

    安装

    yarn add electron-updater
    // 如果没有安装 `electron-builder`, 也一并安装
    

    配置文件

    vue.config.js

    module.exports = {
      pluginOptions: {
        electronBuilder: {
          // List native deps here if they don't work
          // 原生包必须这里声明下
          externals: ["serialport"],
          // If you are using Yarn Workspaces, you may have multiple node_modules folders
          // List them all here so that VCP Electron Builder can find them
          nodeModulesPath: ["../../node_modules", "./node_modules"],
          nodeIntegration: true,
          builderOptions: {
            // options placed here will be merged with default configuration and passed to electron-builder
            appId: "com.grgbanking.screenshow",
            productName: "串口与自动更新", // 项目名,也是生成的安装文件名,即xBox.exe
            copyright: "Copyright © 2020", // 版权信息
            asar: true,
            extraResources: "./extra-resources",
            win: {
              icon: "public/logo.png", 
              // !!!!!!!!!!!!!!重点, 这里必须有publis, 否则打包时不会生成latest.yml文件!!!!!!!!!!!!!!!
              publish: [
                {
                  provider: "generic",
                  url: "http://127.0.0.1:8080/" // 更新文件服务器地址
                }
              ],
              target: [
                {
                  target: "nsis", // 利用nsis制作安装程序
                  arch: [
                    "x64" // 64位
                    // 'ia32'
                  ]
                }
              ]
            },
            linux: {
              icon: "public/logo.png", 
              category: "Graphics",
              target: "snap"
            },
            nsis: {
              oneClick: false, // 是否一键安装
              allowElevation: true, // 允许请求提升。 如果为false,则用户必须使用提升的权限重新启动安装程序。
              allowToChangeInstallationDirectory: true, // 允许修改安装目录
              // installerIcon: "./xxx.ico",// 安装图标
              // uninstallerIcon: "./xxx.ico",//卸载图标
              // installerHeaderIcon: "./xxx.ico", // 安装时头部图标
              createDesktopShortcut: true, // 创建桌面图标
              createStartMenuShortcut: true, // 创建开始菜单图标
              shortcutName: "串口测试" // 图标名称
            }
          }
        }
      }
    };
    

    打包后生成的 latest.yml文件

    打包时必须配置上文的 publish 字段, 否则不生成改文件(在package.json中设置build的做法已经不再支持). 程序更新依赖这个文件做版本判断,作为自动更新的服务器里面必须有这个文件, 否则报错.

    version: 0.2.0 # 与package.json 版本相同, 程序更新必须修改package.json中的version字段
    files:
      - url: 串口与自动更新 Setup 0.2.0.exe
        sha512: 9w2Jps2cg+mjDaHLcCq29cKG48y9DKM5O11leYg0wYhrGUGH8680Z/AEAL207o7LorH3n0h2Dg1HFYuJRpSYkQ==
        size: 56726689
    path: 串口与自动更新 Setup 0.2.0.exe
    sha512: 9w2Jps2cg+mjDaHLcCq29cKG48y9DKM5O11leYg0wYhrGUGH8680Z/AEAL207o7LorH3n0h2Dg1HFYuJRpSYkQ==
    releaseDate: '2021-03-05T04:03:28.119Z'
    

    自动更新程序核心api

    background.ts

    import { app, protocol, BrowserWindow, WebContents, ipcMain } from "electron";
    import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
    // 串口工具
    import SerialPort from "serialport";
    // 自动更新
    import { autoUpdater } from "electron-updater";
    
    console.log("当前平台", process.platform);
    const feedUrl = `http://127.0.0.1:8080/${process.platform}`;
    
    // Scheme must be registered before the app is ready
    protocol.registerSchemesAsPrivileged([
      { scheme: "app", privileges: { secure: true, standard: true } }
    ]);
    
    let webContents: WebContents;
    
    function sendUpdateMessage(message: string, data: unknown) {
      webContents.send("message", { message, data });
    }
    // 检查更新
    function checkForUpdates() {
      // 设置更新服务器的地址, 其实就是一个静态文件服务器地址
      autoUpdater.setFeedURL(feedUrl);
    
      autoUpdater.on("error", function(message) {
        sendUpdateMessage("error", message);
      });
      autoUpdater.on("checking-for-update", function(message) {
        sendUpdateMessage("checking-for-update", message);
      });
      autoUpdater.on("update-available", function(message) {
        sendUpdateMessage("update-available", message);
      });
      autoUpdater.on("update-not-available", function(message) {
        sendUpdateMessage("update-not-available", message);
      });
    
      // 更新下载进度事件
      autoUpdater.on("download-progress", function(progressObj) {
        sendUpdateMessage("downloadProgress", progressObj);
      });
      // 下载完成事件
      autoUpdater.on("update-downloaded", function(
        event,
        releaseNotes,
        releaseName,
        releaseDate,
        updateUrl,
        quitAndUpdate
      ) {
        ipcMain.on("updateNow", (e, arg) => {
          // 停止当前程序并安装
          autoUpdater.quitAndInstall();
        });
        sendUpdateMessage("isUpdateNow", null);
      });
      // 执行检查更新
      autoUpdater.checkForUpdates();
    }
    
    async function createWindow() {
      const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
      });
      webContents = win.webContents;
      if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string);
        if (!process.env.IS_TEST) win.webContents.openDevTools();
      } else {
        createProtocol("app");
        win.loadURL("app://./index.html");
      }
    }
    app.on("ready", async () => {
      createWindow();
      // 测试串口工具
      SerialPort.list().then(ports => {
        console.log(ports);
        const port = new SerialPort("COM4", { autoOpen: true }, function() {
          console.log("open");
        });
        port.write("ROBOT POWER ON", function(err) {
          if (err) {
            return console.log("Error on write: ", err.message);
          }
          console.log("message written");
        });
        port.on("data", data => {
          console.log(data);
        });
      });
      // 检查更新
      setTimeout(checkForUpdates, 1000);
    });
    

    app.vue

    <template>
        <h1>hello world</h1>
    </template>
    <script>
    import { defineComponent } from "vue";
    import { ipcRenderer } from "electron";
    
    export default defineComponent({
      setup() {
        ipcRenderer.on("message", (event, { message, data }) => {
          console.log(message, data);
          switch (message) {
            case "isUpdateNow":
              if (confirm("现在更新?")) {
                ipcRenderer.send("updateNow");
              }
              break;
            default:
              document.querySelector("h1").innerHTML = message;
              break;
          }
        });
      }
    });
    </script>
    

    静态资源服务器

    基于 express的静态资源服务器, 这里要注意的是更新服务器静态文件资源是最新打包后的文件, 需要更新 package.json 中版本号.

    const express = require("express");
    const app = express();
    const port = 8080;
    app.use(express.static("./public"));
    app.get("/", (req, res) => {
      res.send("Hello World!");
    });
    
    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`);
    });
    

    其中 public 文件夹中有个win32 文件夹, 对应了查找更新文件的地址const feedUrl = http://127.0.0.1:8080/${process.platform};, 其中 process.platform 的值在 windows 中为 win32, 下面是 win32 中存的打包后的文件:

    ├─latest.yml
    ├─串口与自动更新 Setup 0.1.0.exe
    ├─win-unpacked  # 这个也是非必须
    

    其中 串口与自动更新 Setup 0.1.0.exe 安装程序和 win-unpacked 只要一个即可, 另外 win-unpacked 文件夹名字可以任意取, 或者把里面的文件放到 latest.yml 同一目录也可.

    相关文章

      网友评论

          本文标题:配置electron应用自动更新

          本文链接:https://www.haomeiwen.com/subject/vqirqltx.html