Electron應用使用electron-builder配合electron-updater實現自動更新(windows + mac)


最新博文地址:https://segmentfault.com/a/1190000012904543

 

發客戶端一定要做的就是自動更新模塊,否則每次版本升級都是一個頭疼的事。
下面是Electron應用使用electron-builder配合electron-updater實現自動更新的解決方案。

1.安裝 electron-updater 包模塊

npm install electron-updater --save

2.配置package.json文件

為了打包時生成latest.yml文件,需要在 build 參數中添加 publish 配置。

"build": {
    "productName": "***",//隱藏軟件名稱
    "appId": "**",//隱藏appid
    "directories": {
      "output": "build"
    },
    "publish": [
      {
        "provider": "generic",
        "url": "http://**.**.**.**:3002/download/",//隱藏版本服務器地址
      }
    ],
    "files": [
      "dist/electron/**/*"
    ],
    "dmg": {
      "contents": [
        {
          "x": 410,
          "y": 150,
          "type": "link",
          "path": "/Applications"
        },
        {
          "x": 130,
          "y": 150,
          "type": "file"
        }
      ]
    },
    "mac": {
      "icon": "build/icons/icon.icns",
      "artifactName": "${productName}_setup_${version}.${ext}"
    },
    "win": {
      "icon": "build/icons/icon.ico",
      "artifactName": "${productName}_setup_${version}.${ext}"
    },
    "linux": {
      "icon": "build/icons",
      "artifactName": "${productName}_setup_${version}.${ext}"
    }
  }

  注意:配置了publish才會生成latest.yml文件,用於自動更新的配置信息;
3.配置主進程main.js文件(或主進程main中的index.js文件),引入 electron-updater 文件,添加自動更新檢測和事件監聽:
注意:一定要是主進程main.js文件(或主進程main中的index.js文件),否則會報錯。

import { app, BrowserWindow, ipcMain } from 'electron'

// 注意這個autoUpdater不是electron中的autoUpdater
import { autoUpdater } from "electron-updater"
import {uploadUrl} from "../renderer/config/config";

// 檢測更新,在你想要檢查更新的時候執行,renderer事件觸發后的操作自行編寫
function updateHandle() {
  let message = {
    error: '檢查更新出錯',
    checking: '正在檢查更新……',
    updateAva: '檢測到新版本,正在下載……',
    updateNotAva: '現在使用的就是最新版本,不用更新',
  };
  const os = require('os');

  autoUpdater.setFeedURL(uploadUrl);
  autoUpdater.on('error', function (error) {
    sendUpdateMessage(message.error)
  });
  autoUpdater.on('checking-for-update', function () {
    sendUpdateMessage(message.checking)
  });
  autoUpdater.on('update-available', function (info) {
    sendUpdateMessage(message.updateAva)
  });
  autoUpdater.on('update-not-available', function (info) {
    sendUpdateMessage(message.updateNotAva)
  });

  // 更新下載進度事件
  autoUpdater.on('download-progress', function (progressObj) {
    mainWindow.webContents.send('downloadProgress', progressObj)
  })
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {

    ipcMain.on('isUpdateNow', (e, arg) => {
      console.log(arguments);
      console.log("開始更新");
      //some code here to handle event
      autoUpdater.quitAndInstall();
    });

    mainWindow.webContents.send('isUpdateNow')
  });

  ipcMain.on("checkForUpdate",()=>{
      //執行自動更新檢查
      autoUpdater.checkForUpdates();
  })
}

// 通過main進程發送事件給renderer進程,提示更新信息
function sendUpdateMessage(text) {
  mainWindow.webContents.send('message', text)
}

  4.在視圖層中觸發自動更新,並添加自動更新事件的監聽。
觸發自動更新:

ipcRenderer.send("checkForUpdate");

  監聽自動更新事件:

 import { ipcRenderer } from "electron";
  ipcRenderer.on("message", (event, text) => {
            console.log(arguments);
            this.tips = text;
        });
        ipcRenderer.on("downloadProgress", (event, progressObj)=> {
            console.log(progressObj);
            this.downloadPercent = progressObj.percent || 0;
        });
        ipcRenderer.on("isUpdateNow", () => {
            ipcRenderer.send("isUpdateNow");
        });

  為避免多次切換頁面造成監聽的濫用,切換頁面前必須移除監聽事件:

//組件銷毀前移除所有事件監聽channel
        ipcRenderer.removeAll(["message", "downloadProgress", "isUpdateNow"]);//remove只能移除單個事件,單獨封裝removeAll移除所有事件

  5.項目打包
執行electron-builder進行打包,windows下會生成安裝包exe和latest.yml等文件,執行exe安裝軟件;Mac下會生成安裝包dmg和latest-mac.yml文件,執行dmg安裝軟件。
windows打包生成文件:

Mac打包生成文件:

6.軟件升級版本,修改package.json中的version屬性,例如:改為 version: “1.1.0” (之前為1.0.0);
7.再次執行electron-builder打包,將新版本latest.yml文件和exe文件放到package.json中build -> publish中的url對應的地址下;
8.在應用中觸發更新檢查,electron-updater自動會通過對應url下的yml文件檢查更新;

windows上自動更新示例:

 

 mac上自動更新示例:

 如果這篇文章對你的工作或者學習有幫助的話,請收藏或點個贊。如果對其中有什么不明白的或者報錯,可以留言或者加QQ群140455228交流


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM