说明如何在你的 Electron 软件中接入本更新中心,实现自动更新。
npm install electron-updater在 main.js(或主进程入口)中添加:
const { app } = require('electron');
const { autoUpdater } = require('electron-updater');
// 更新服务器地址
const UPDATE_URL = 'https://cmupdate.mengjun.icu';
// 设置更新源
autoUpdater.setFeedURL({
provider: 'generic',
url: UPDATE_URL
});
app.whenReady().then(() => {
// 创建窗口等...
// 启动后检查更新
autoUpdater.checkForUpdates();
});
// 下载完成后重启安装
autoUpdater.on('update-downloaded', () => {
const { dialog } = require('electron');
dialog.showMessageBox({
type: 'info',
title: '更新就绪',
message: '新版本已下载,是否立即重启?',
buttons: ['立即重启', '稍后']
}).then(({ response }) => {
if (response === 0) {
autoUpdater.quitAndInstall();
}
});
});
在 package.json 的 build 中:
{
"build": {
"publish": {
"provider": "generic",
"url": "https://cmupdate.mengjun.icu"
}
}
}
Windows 自动更新基于 Squirrel.Windows,electron-builder 使用 NSIS 目标时会生成:
| 文件 | 用途 |
|---|---|
| .exe / .msi | 首次安装 |
| .nupkg | 自动更新(必需) |
.nupkg是 NuGet Package 格式,本质是 zip,内含更新文件和版本信息。Squirrel 通过它实现增量更新。
使用 nsis目标打包会同时生成: 你的应用-1.0.0-setup.exe和 你的应用-1.0.0-full.nupkg,二者都需上传。
// package.json 中
"build": {
"win": {
"target": ["nsis"]
}
}打包命令: npx electron-builder --win
.exe和 .nupkg(Windows)→ 点击「立即发布」| 项目 | 说明 |
|---|---|
| 更新地址 | https://cmupdate.mengjun.icu |
| setFeedURL | 与 publish.url 保持一致 |
| checkForUpdates() | 在 app.whenReady() 之后调用 |
| quitAndInstall() | 下载完成后调用,重启并安装 |
autoUpdater.on('update-available', (info) => {
console.log('发现新版本:', info.version);
});
autoUpdater.on('update-not-available', () => {
console.log('已是最新');
});
autoUpdater.on('download-progress', (progress) => {
console.log('下载进度:', progress.percent + '%');
});
autoUpdater.on('error', (err) => {
console.error('更新失败:', err);
});
使用「版本类型(Flavor)」区分不同软件,一个 Flavor 对应一个独立应用。
每个软件创建一个 Flavor,例如:
单应用可直接使用默认的 default。
添加新版本时,在「版本类型」下拉框中选择该软件对应的 Flavor。
在各自的主进程中,将 setFeedURL的 url指向该软件专属路径:
// 软件 A(版本类型:橙猫AI)
autoUpdater.setFeedURL({
provider: 'generic',
url: 'https://cmupdate.mengjun.icu/update/flavor/橙猫AI'
});
// 软件 B(版本类型:ToolB)
autoUpdater.setFeedURL({
provider: 'generic',
url: 'https://cmupdate.mengjun.icu/update/flavor/ToolB'
});
// 单应用或使用 default 时
autoUpdater.setFeedURL({
provider: 'generic',
url: 'https://cmupdate.mengjun.icu'
});注意: Flavor 名称需与后台完全一致(区分大小写),建议用英文或拼音,避免特殊字符。