electron-vue使用electron-updater實現自動更新

今天呢,給你們帶來一篇乾貨滿滿的electron-vue自動升級的教程,話很少說,開始個人表演!vue

clipboard.png


配置文件 "package.json"
"build" : {
    "publish": [
      {
        "provider": "generic",
        "url": "http://127.0.0.1:3000/newfile/"
      }
    ],
},
"devDependencies": {
    "electron": "^2.0.4",
    "electron-updater": "3.0.0",
    "electron-builder": "^20.19.2"
}

build字段詳細配置node

安裝依賴
須要注意的是electron-vue中目前是使用electron 2.0.4的,因此最新版的electron-updater是不支持的,若手動升級electron版本的話,若是你使用了node-ffi等的話,是沒法運行的,可是若是你只是使用node-ffi的話能夠切換成node-ffi-napi而後對electron進行升級
yarn add electron-updater@3.0.0 --dev(推薦)
npm i electron-updater@3.0.0 -D
cnpm i electron-updater@3.0.0 -D
自動更新 "update.js"
import { autoUpdater } from 'electron-updater'
import { ipcMain } from 'electron'
/**
 * -1 檢查更新失敗 0 正在檢查更新 1 檢測到新版本,準備下載 2 未檢測到新版本 3 下載中 4 下載暫停 5 下載暫停恢復 6 下載完成 7 下載失敗 8 取消下載
 * */
class Update {
  mainWindow
  constructor (mainWindow) {
    this.mainWindow = mainWindow
    autoUpdater.setFeedURL('http://127.0.0.1:3000/newfile') // 更新地址與package.json中的build.publish.url相對應
    /**
    * 根據自身需求選擇下方方法
    */
    this.error()
    this.start()
    this.allow()
    this.unallowed()
    this.listen()
    this.download()
  }
  Message (type, data) {
    this.mainWindow.webContents.send('message', type, data)
  }
  error () { // 當更新發生錯誤的時候觸發。
    autoUpdater.on('error', (err) => {
      this.Message(-1, err)
      console.log(err)
    })
  }
  start () { // 當開始檢查更新的時候觸發
    autoUpdater.on('checking-for-update', (event, arg) => {
      this.Message(0)
    })
  }
  allow () { // 發現可更新數據時
    autoUpdater.on('update-available', (event, arg) => {
      this.Message(1)
    })
  }
  unallowed () { // 沒有可更新數據時
    autoUpdater.on('update-not-available', (event, arg) => {
      this.Message(2)
    })
  }
  listen () { // 下載監聽
    autoUpdater.on('download-progress', () => {
      this.Message('下載進行中')
    })
  }
  download () { // 下載完成
    autoUpdater.on('update-downloaded', () => {
      this.Message(6)
      setTimeout(m => {
        autoUpdater.quitAndInstall()
      }, 1000)
    })
  }
  load () { // 觸發器
    autoUpdater.checkForUpdates()
  }
}
export default Update

update配置
若對class寫法不是很熟悉的同窗,能夠參考阮一峯老師的es6課程class
在下載中的時候有一個問題就是下載非差別文件的時候不會觸發下載監聽,點擊查看git

主進程 "index.js"
import Update from './update'
  mainWindow = new BrowserWindow({
  height: 563,
  useContentSize: true,
  width: 1000
})
let update = new Update(mainWindow)
下面對比較常見的一些bug進行一下處理
At least electron-updater 4.0.0 is recommended by current electron-builder version. Please set electron-updater version to "^4.0.0"

electron-updater 安裝在dependencies了,在package.json中將他移動到devDependencieses6

相關文章
相關標籤/搜索