跳到主要内容

自动更新

自动更新之前先做好自动发布

https://www.electron.build/configuration/publish.html

electron-builder已经做好了自动发布,我们填一个publish字段,填一个github即可。 触发条件: Value | Description ------- | ------- onTag | on tag push only onTagOrDraft | on tag push or if draft release exists always | always publish never | never publish

But please consider using automatic rules instead of explicitly specifying publish:

  • If CI server detected, — onTagOrDraft.
  • If CI server reports that tag was pushed, — onTag. Release will be drafted (if doesn’t already exist) and artifacts published only if tag was pushed.
  • If npm script named release, — always. 最后一条说明可以通过release指令触发。

需要设置一个GH_TOKEN的环境变量来访问github

 "scripts": {
"release": "cross-env GH_TOKEN=********** electron-builder",
"prerelease": "npm run build"
}
"publish": [
"github"
],

自动更新

首先自动更新的时候需要release命令执行后的一些yml文件,所以发布尽量采用release模式。

如果需要在开发环境需要测试自动更新可以用本地的dev-app-update.yml,去指定到那个git的库的release去拉取是否需要更新,如果是就下载

const { autoUpdater } = require('electron-updater');
app.on('ready', () => {
autoUpdater.autoDownload = false
if (isDev) {
// autoUpdater.updateConfigPath = path.join(__dirname, 'dev-app-update.yml') // 本地调试自动更新
// autoUpdater.checkForUpdates() // 本地检查更新
} else {
autoUpdater.checkForUpdatesAndNotify() // 线上检查更新
}

autoUpdater.on('error', (error) => {
dialog.showErrorBox('Error: ', error == null ? "unknown" : (error.stack || error).toString())
})
autoUpdater.on('checking-for-update', () => {
console.log('Checking for update...');
})
autoUpdater.on('update-available', () => {
dialog.showMessageBox({
type: 'info',
title: '应用有新的版本',
message: '发现新版本,是否现在更新?',
buttons: ['是', '否']
}, (buttonIndex) => {
if (buttonIndex === 0) {
autoUpdater.downloadUpdate()
}
})
})
autoUpdater.on('update-not-available', () => {
dialog.showMessageBox({
title: '没有新版本',
message: '当前已经是最新版本'
})
})
autoUpdater.on('download-progress', (progressObj) => {
let log_message = "Download speed: " + progressObj.bytesPerSecond;
log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
console.log(log_message)
})

autoUpdater.on('update-downloaded', () => {
dialog.showMessageBox({
title: '安装更新',
message: '更新下载完毕,应用将重启并进行安装'
}, () => {
setImmediate(() => autoUpdater.quitAndInstall())
})
})
}