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

最新博文地址:http://www.javashuo.com/article/p-fwodovvw-ku.htmljavascript

 

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

1.安裝 electron-updater 包模塊linux

npm install electron-updater --save

2.配置package.json文件web

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

"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文件),不然會報錯。json

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.在視圖層中觸發自動更新,並添加自動更新事件的監聽。
觸發自動更新:segmentfault

ipcRenderer.send("checkForUpdate");

  監聽自動更新事件:windows

 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打包生成文件:app

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交流

相關文章
相關標籤/搜索