electron+vue3实现自动更新的示例代码

 更新时间:2025年10月24日 11:41:49   作者:ok云科技  
本文主要介绍了electron+vue3实现自动更新的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1. 下载更新插件

 npm install electron-log --save
 npm install electron-updater --save

2.electron主进程添加更新

2.1 更新封装

// electron/ipc/api/updater.js
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,    // 记录下载进度百分比 (0-100)
  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()

    // 如果没有找到更新,autoUpdater 会触发 'update-not-available' 事件
    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() {

   ......
   // 1 设置主窗口引用给更新模块
   setMainWindow(mainWindow)

  // 2 初始化自动更新(仅生产环境)
  if (!config.isDev) {
    initializeAutoUpdater()

     // 应用加载完成后自动检查更新
    mainWindow.webContents.once('did-finish-load', () => {
      setTimeout(() => {
        console.log('应用加载完成,开始自动检查更新...')
        // 通过 IPC 调用检查更新
        mainWindow.webContents.send('updater:autoCheck')
      }, 3000)
    })
  }
  
  // 监听窗口关闭后事件
  mainWindow.on('closed', () => {
    console.log('mainWindow closed', " 主进程关闭 窗口已关闭...")
    mainWindow = null
    // 3删除主窗口引用
    setMainWindow(null)
  })
    
}

2.3 维护preload.js

3 渲染进程封装组件

// electron更新组件
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 测试更新

打包一个低版本-> 安装使用 -> 开始就会检查版本,如果有新的版本提示是否安装 -> 是 退出安装,否 稍后安装!
注意:设置了环境只有生产环境才会检查!

到此这篇关于electron+vue3实现自动更新的示例代码的文章就介绍到这了,更多相关electron vue3自动更新内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • vue history模式刷新404原因及解决方法

    vue history模式刷新404原因及解决方法

    vue路由的URL有两种模式,一种是 hash,一种是history,下面这篇文章主要给大家介绍了关于vue history模式刷新404原因及解决方法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-09-09
  • Vue3 源码解读静态提升详解

    Vue3 源码解读静态提升详解

    这篇文章主要为大家介绍了Vue3源码解读静态提升示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • vue2.0构建单页应用最佳实战

    vue2.0构建单页应用最佳实战

    这篇文章主要为大家分享了vue2.0构建单页应用最佳实战案例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04
  • 前端Vue3最常用的 20 道面试题总结(含详细解释和代码示例)

    前端Vue3最常用的 20 道面试题总结(含详细解释和代码示例)

    Vue3作为当前前端主流框架,其核心特性、底层原理及生态工具是面试中的高频考点,这篇文章主要介绍了前端Vue3最常用的20道面试题(含详细解释和代码示例)的相关资料,需要的朋友可以参考下
    2026-05-05
  • vue实现移动端项目多行文本溢出省略

    vue实现移动端项目多行文本溢出省略

    这篇文章主要介绍了vue实现移动端项目多行文本溢出省略功能,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-07-07
  • 详解webpack打包vue时提取css

    详解webpack打包vue时提取css

    本篇文章主要介绍了详解webpack打包vue时提取css,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • vue-cli中的webpack的config配置全过程

    vue-cli中的webpack的config配置全过程

    文章详细介绍了Vue CLI中webpack的配置文件,包括`dev.env.js`和`prod.env.js`的内容,以及它们是如何通过`webpack-merge`模块进行合并的,文章还解释了这些配置文件中各个参数的作用,如`assetsSubDirectory`、`assetsPublicPath`、`proxyTable`等
    2026-02-02
  • Vue使用sign-canvas实现在线手写签名的实例

    Vue使用sign-canvas实现在线手写签名的实例

    sign-canvas 一个基于 canvas 开发,封装于 Vue 组件的通用手写签名板(电子签名板),支持 pc 端和移动端,本文给大家分享Vue使用sign-canvas实现在线手写签名,感兴趣的朋友一起看看吧
    2022-05-05
  • vue的组件通讯方法总结大全

    vue的组件通讯方法总结大全

    这篇文章主要为大家介绍了非常全面vue的组件通讯方法总结,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • vue-draggable实现拖拽表单的示例代码

    vue-draggable实现拖拽表单的示例代码

    本文主要介绍了vue-draggable实现拖拽表单的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-05-05

最新评论