Skip to content

electron-updater检测更新版本

在 Electron 应用中使用 electron-updater 来实现自动检测和下载更新是一个非常实用的功能。以下是如何在你的 Electron 应用中集成 electron-updater 的步骤:

  1. 安装依赖: 首先,你需要在你的项目中安装 electron-updaterbuilder-util-runtime 这两个模块。可以通过运行以下命令来完成安装:

    bash
    npm install electron-updater builder-util-runtime --save
  2. 配置 main.js: 在你的主进程文件(通常是 main.jsmain.ts)中,引入并配置 autoUpdater 模块。这里是一个基本的示例:

    javascript
    const { autoUpdater } = require('electron-updater');
    const log = require('electron-log');
    
    // 设置日志输出
    autoUpdater.logger = log;
    autoUpdater.logger.transports.file.level = 'info';
    
    function checkForUpdates() {
      log.info('Checking for updates...');
      autoUpdater.checkForUpdates();
    }
    
    autoUpdater.on('checking-for-update', () => {
      log.info('Checking for update...');
    });
    
    autoUpdater.on('update-available', (info) => {
      log.info('Update available.');
    });
    
    autoUpdater.on('update-not-available', (info) => {
      log.info('Update not available.');
    });
    
    autoUpdater.on('error', (err) => {
      log.error('Error in auto-updater: ', err);
    });
    
    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})`;
      log.info(log_message);
    });
    
    autoUpdater.on('update-downloaded', (info) => {
      log.info('Update downloaded; will be applied on restart.');
      autoUpdater.quitAndInstall();
    });
    
    app.on('ready', checkForUpdates);
  3. 设置服务器: 你需要一个服务器来托管你的应用更新文件。electron-updater 默认使用 GitHub 作为更新服务器,但你也可以使用自定义的服务器。如果使用 GitHub,确保你的仓库是公开的,并且在 main.js 中正确配置 autoUpdaterfeedURL

  4. 构建和发布: 使用 electron-builder 构建你的应用,并将其上传到你的更新服务器。确保在构建时使用了正确的配置选项来包含 electron-updater

  5. 测试更新: 最后,确保在真实环境中测试更新功能,以确保一切按预期工作。

这只是一个基础的指南,实际应用中可能需要根据具体需求进行更详细的配置。例如,你可能需要处理用户界面的更新通知、错误处理等。希望这能帮助你开始在 Electron 应用中实现自动更新功能!