Electron 更新器入门
本指南将引导您在 Electron 应用程序中设置 @capgo/electron-updater 以启用实时 JavaScript/HTML/CSS 更新。
- Electron 20.0.0 或更高版本
- Node.js 18 或更高
- Capgo 帐户(在 capgo.app 上注册)
-
安装包:
Terminal window npm install @capgo/electron-updater -
从 Capgo 仪表板获取您的应用程序 ID。如果您尚未创建应用程序,请运行:
Terminal window npx @capgo/cli@latest init
Electron Updater 需要在三个地方进行设置:主进程、预加载脚本和渲染器进程。
import { app, BrowserWindow } from 'electron';import * as path from 'path';import { ElectronUpdater, setupIPCHandlers, setupEventForwarding,} from '@capgo/electron-updater';
// Create updater instance with your Capgo App IDconst updater = new ElectronUpdater({ appId: 'YOUR_CAPGO_APP_ID', // e.g., '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, }, });
// Initialize updater with window and builtin path const builtinPath = path.join(__dirname, 'www/index.html'); await updater.initialize(mainWindow, builtinPath);
// Setup IPC communication between main and renderer setupIPCHandlers(updater); setupEventForwarding(updater, mainWindow);
// Load the current bundle (either builtin or downloaded update) await mainWindow.loadFile(updater.getCurrentBundlePath());});
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); }});import { exposeUpdaterAPI } from '@capgo/electron-updater/preload';
// Expose the updater API to the renderer processexposeUpdaterAPI();// renderer.ts (or in your app's entry point)import { requireUpdater } from '@capgo/electron-updater/renderer';
const updater = requireUpdater();
// CRITICAL: Call this on every app launch!// This confirms the bundle loaded successfully and prevents rollbackawait updater.notifyAppReady();
console.log('App ready, current bundle:', await updater.current());使用 autoUpdate: true,更新程序会自动检查更新。您还可以触发手动检查:
// Check for updates manuallyconst latest = await updater.getLatest();
if (latest.url && !latest.error) { console.log('Update available:', latest.version);
// Download the update const bundle = await updater.download({ url: latest.url, version: latest.version, checksum: latest.checksum, });
console.log('Downloaded bundle:', bundle.id);
// Option 1: Queue for next restart await updater.next({ id: bundle.id });
// Option 2: Apply immediately and reload // await updater.set({ id: bundle.id });}通过事件跟踪更新进度和状态:
// Download progressupdater.addListener('download', (event) => { console.log(`Download progress: ${event.percent}%`);});
// Update availableupdater.addListener('updateAvailable', (event) => { console.log('New version available:', event.bundle.version);});
// Download completedupdater.addListener('downloadComplete', (event) => { console.log('Download finished:', event.bundle.id);});
// Update failedupdater.addListener('updateFailed', (event) => { console.error('Update failed:', event.bundle.version);});使用 Capgo CLI 上传更新:
# Build your appnpm run build
# Upload to Capgonpx @capgo/cli@latest bundle upload --channel=production您的 Electron 应用程序将在下次检查时自动检测并下载新包。
在开发过程中启用调试菜单:
const updater = new ElectronUpdater({ appId: 'YOUR_CAPGO_APP_ID', debugMenu: true, // Enable debug menu});按“Ctrl+Shift+D”(或 Mac 上的“Cmd+Shift+D”)打开调试菜单,然后:
- 查看当前捆绑包信息
- 在可用捆绑包之间切换
- 重置为内置版本
- 查看设备和频道信息
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)});