跳转到内容

Electron Updater 入门

本指南将引导您在 Electron 应用中设置 @capgo/electron-updater,以启用 JavaScript/HTML/CSS 的实时更新。

  • Electron 20.0.0 或更高版本
  • Node.js 18 或更高版本
  • Capgo 账号(在 capgo.app 注册)
  1. 安装包:

    Terminal window
    npm install @capgo/electron-updater
  2. 在 Capgo 控制台获取 App ID。如果尚未创建应用,请运行:

    Terminal window
    npx @capgo/cli@latest init

Electron Updater 需要在三处配置:主进程、预加载脚本、渲染进程。

main.ts
import { app, BrowserWindow } from 'electron';
import * as path from 'path';
import {
ElectronUpdater,
setupIPCHandlers,
setupEventForwarding,
} from '@capgo/electron-updater';
// 使用您的 Capgo App ID 创建 updater 实例
const updater = new ElectronUpdater({
appId: 'YOUR_CAPGO_APP_ID', // 例如 'com.example.myapp'
autoUpdate: true,
});
app.whenReady().then(async () => {
const mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
},
});
// 使用窗口与内置路径初始化 updater
const builtinPath = path.join(__dirname, 'www/index.html');
await updater.initialize(mainWindow, builtinPath);
// 设置主进程与渲染进程之间的 IPC 通信
setupIPCHandlers(updater);
setupEventForwarding(updater, mainWindow);
// 加载当前 bundle(内置或下载的更新)
await mainWindow.loadFile(updater.getCurrentBundlePath());
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
preload.ts
import { exposeUpdaterAPI } from '@capgo/electron-updater/preload';
// 将 updater API 暴露给渲染进程
exposeUpdaterAPI();
// renderer.ts (或应用入口文件)
import { requireUpdater } from '@capgo/electron-updater/renderer';
const updater = requireUpdater();
// 关键:每次应用启动时都要调用!
// 该调用确认 bundle 成功加载并防止回滚
await updater.notifyAppReady();
console.log('App ready, current bundle:', await updater.current());

autoUpdate: true 时,updater 会自动检查更新。您也可以手动触发:

// 手动检查更新
const latest = await updater.getLatest();
if (latest.url && !latest.error) {
console.log('Update available:', latest.version);
// 下载更新
const bundle = await updater.download({
url: latest.url,
version: latest.version,
checksum: latest.checksum,
});
console.log('Downloaded bundle:', bundle.id);
// 选项 1: 下次重启生效
await updater.next({ id: bundle.id });
// 选项 2: 立即应用并重载
// await updater.set({ id: bundle.id });
}

通过事件跟踪更新进度与状态:

// 下载进度
updater.addListener('download', (event) => {
console.log(`Download progress: ${event.percent}%`);
});
// 有可用更新
updater.addListener('updateAvailable', (event) => {
console.log('New version available:', event.bundle.version);
});
// 下载完成
updater.addListener('downloadComplete', (event) => {
console.log('Download finished:', event.bundle.id);
});
// 更新失败
updater.addListener('updateFailed', (event) => {
console.error('Update failed:', event.bundle.version);
});

使用 Capgo CLI 上传更新:

Terminal window
# 构建应用
npm run build
# 上传到 Capgo
npx @capgo/cli@latest bundle upload --channel=production

您的 Electron 应用将在下次检查时自动检测并下载新 bundle。

在开发期间启用调试菜单:

const updater = new ElectronUpdater({
appId: 'YOUR_CAPGO_APP_ID',
debugMenu: true, // 启用调试菜单
});

Ctrl+Shift+D(或 Mac 上 Cmd+Shift+D) 打开调试菜单,可:

  • 查看当前 bundle 信息
  • 在可用 bundle 之间切换
  • 重置为内置版本
  • 查看设备与渠道信息
const updater = new ElectronUpdater({
// Required
appId: 'com.example.app',
// Server URLs (defaults to Capgo Cloud)
updateUrl: 'https://plugin.capgo.app/updates',
channelUrl: 'https://plugin.capgo.app/channel_self',
statsUrl: 'https://plugin.capgo.app/stats',
// Behavior
autoUpdate: true, // Enable auto-updates
appReadyTimeout: 10000, // MS before rollback (default: 10s)
autoDeleteFailed: true, // Delete failed bundles
autoDeletePrevious: true, // Delete old bundles after successful update
// Channels
defaultChannel: 'production',
// Security
publicKey: '...', // For end-to-end encryption
// Debug
debugMenu: false, // Enable debug menu
disableJSLogging: false, // Disable console logs
// Periodic Updates
periodCheckDelay: 0, // Seconds between checks (0 = disabled, min 600)
});