场景

由于生产应用希望在有新版本时,自动为用户推送更新,所以此处便写一下如何让 electron 程序自动更新。

安装 npm 包

cd apps/main/ && yarn add electron-updater

配置 electron-builder

参考: https://www.electron.build/auto-updateopen in new window

其实本质上就是配置一个网络可以访问到的静态资源目录,这里使用了一个本地的静态资源服务器,指向目录是 apps/main/release(即打包而进程程序的目录)

{
  "build": {
    "publish": [
      {
        "provider": "generic",
        "url": "http://localhost:8080/"
      }
    ]
  }
}

启动时检查更新

在主进程添加检查更新的代码,并自定义提示文案。

await autoUpdater.checkForUpdates()
autoUpdater.addListener('update-downloaded', (info) => {
  new Notification({
    title: '更新提醒',
    body: `新版本 ${info.version} 已经准备好,点击立刻更新!`,
  })
    .addListener('click', () => {
      autoUpdater.quitAndInstall()
    })
    .show()
})

效果

现在,你可以启动一个本地静态服务器指向 apps/main/release,例如 live-serveropen in new window,然后打包一个新版本,再启动旧的程序就可以了。

效果