1. 下载更新插件
npm install electron-log --save
npm install electron-updater --save
2.electron主进程添加更新
2.1 更新封装
const { autoUpdater } = require('electron-updater')
const { dialog, BrowserWindow } = require('electron')
const log = require('electron-log')
autoUpdater.logger = log
autoUpdater.logger.transports.file.level = 'info'
let updateState = {
isChecking: false,
isDownloading: false,
downloadProgress: 0,
lastError: null,
updateAvailable: false,
updateDownloaded: false
}
let mainWindow = null
function setMainWindow(window) {
mainWindow = window
}
async function checkForUpdates(event, options = {}) {
if (updateState.isChecking) {
return { success: false, message: '正在检查更新中...' }
}
try {
updateState.isChecking = true
updateState.lastError = null
console.log('开始检查更新...')
if (mainWindow) {
mainWindow.webContents.send('updater:updateMessage', '正在检查更新...')
}
const result = await autoUpdater.checkForUpdates()
if (result) {
console.log('发现更新:', result.updateInfo.version)
return {
success: true,
message: `发现新版本 v${result.updateInfo.version}`,
version: result.updateInfo.version
}
}
return { success: true, message: '正在检查更新...' }
} catch (error) {
console.error('检查更新失败:', error)
updateState.lastError = error.message
if (mainWindow) {
mainWindow.webContents.send('updater:updateError', error.message)
}
return {
success: false,
message: `检查更新失败: ${error.message}`
}
} finally {
updateState.isChecking = false
}
}
async function quitAndInstall(event) {
try {
console.log('准备退出并安装更新...')
autoUpdater.quitAndInstall()
return { success: true }
} catch (error) {
console.error('安装更新失败:', error)
return {
success: false,
message: `安装更新失败: ${error.message}`
}
}
}
async function getUpdateStatus(event) {
return {
...updateState,
currentVersion: require('../../package.json').version
}
}
function initializeAutoUpdater() {
autoUpdater.on('checking-for-update', () => {
console.log('正在检查更新...')
updateState.isChecking = true
if (mainWindow) {
mainWindow.webContents.send('updater:updateMessage', '正在检查更新...')
}
})
autoUpdater.on('update-available', (info) => {
console.log('发现新版本:', info.version)
updateState.updateAvailable = true
updateState.isChecking = false
if (mainWindow) {
mainWindow.webContents.send('updater:updateAvailable', info)
mainWindow.webContents.send('updater:updateMessage', `发现新版本 v${info.version},正在下载...`)
}
if (mainWindow && process.env.NODE_ENV !== 'development') {
dialog.showMessageBox(mainWindow, {
type: 'info',
title: '发现新版本',
message: `发现新版本 v${info.version}`,
detail: '新版本正在后台下载,下载完成后将提示您安装。',
buttons: ['确定']
})
}
})
autoUpdater.on('update-not-available', (info) => {
console.log('当前已是最新版本')
updateState.isChecking = false
updateState.updateAvailable = false
if (mainWindow) {
mainWindow.webContents.send('updater:updateNotAvailable', info)
mainWindow.webContents.send('updater:updateMessage', '当前已是最新版本')
}
})
autoUpdater.on('download-progress', (progressObj) => {
updateState.isDownloading = true
updateState.downloadProgress = Math.floor(progressObj.percent)
const progressMessage = `下载进度: ${progressObj.percent}% (${progressObj.transferred}/${progressObj.total})`
console.log(progressMessage)
if (mainWindow) {
mainWindow.webContents.send('updater:downloadProgress', progressObj)
mainWindow.webContents.send('updater:updateMessage', progressMessage)
}
})
autoUpdater.on('update-downloaded', (info) => {
console.log('更新下载完成,准备安装')
updateState.isDownloading = false
updateState.updateDownloaded = true
updateState.downloadProgress = 100
if (mainWindow) {
mainWindow.webContents.send('updater:updateDownloaded', info)
mainWindow.webContents.send('updater:updateMessage', '更新下载完成,准备安装')
}
if (mainWindow && process.env.NODE_ENV !== 'development') {
dialog.showMessageBox(mainWindow, {
type: 'info',
title: '更新就绪',
message: `新版本 v${info.version} 已下载完成`,
detail: '应用将在关闭后自动安装更新。',
buttons: ['立即重启', '稍后重启']
}).then((result) => {
if (result.response === 0) {
autoUpdater.quitAndInstall()
}
})
}
})
autoUpdater.on('error', (err) => {
console.error('更新错误:', err)
updateState.isChecking = false
updateState.isDownloading = false
updateState.lastError = err.message
if (mainWindow) {
mainWindow.webContents.send('updater:updateError', err.message)
mainWindow.webContents.send('updater:updateMessage', `更新错误: ${err.message}`)
}
})
console.log('自动更新监听器初始化完成')
}
module.exports = {
checkForUpdates,
quitAndInstall,
getUpdateStatus,
initializeAutoUpdater,
setMainWindow
}
2.2 主进程添加更新检查
const { initializeAutoUpdater, setMainWindow } = require(path.resolve(__dirname, '../ipc/api/updater'))
function createWindow() {
......
setMainWindow(mainWindow)
if (!config.isDev) {
initializeAutoUpdater()
mainWindow.webContents.once('did-finish-load', () => {
setTimeout(() => {
console.log('应用加载完成,开始自动检查更新...')
mainWindow.webContents.send('updater:autoCheck')
}, 3000)
})
}
mainWindow.on('closed', () => {
console.log('mainWindow closed', " 主进程关闭 窗口已关闭...")
mainWindow = null
setMainWindow(null)
})
}
2.3 维护preload.js
3 渲染进程封装组件
import AppUpdater from '@/components/AppUpdater'
APP.VUE中引用组件
<template>
<!-- element-plus 国际化组件处理 -->
<el-config-provider :locale="elementLocales[effectiveLang]">
<router-view />
<AppUpdater />
</el-config-provider>
</template>
4 配置 package.json
"build": {
......
"publish": [
{
"provider": "github",
"owner": "github用户名",
"repo": "github项目名"
}
],
......
5 github上维护最新版本
5.1 创建仓库
5.2 创建release
项目右侧-> 点击release -> New 或者 Draft a new release -> new Tag -> 写 release title -> 上传文件:
1 可执行的安装文件;
2 latest0tml 文件;
-> 最后 Publish release
6 测试更新
打包一个低版本-> 安装使用 -> 开始就会检查版本,如果有新的版本提示是否安装 -> 是 退出安装,否 稍后安装!
注意:设置了环境只有生产环境才会检查!