electron-vue项目 自动更新解决方案(附代码)

electron-vue的创建过程这里不再赘述。相信已经搜索到这篇文章的你,已经完成了这个过程,下面我们进入正题

 

前言

如果您的electron版本还是2.xx版本,需要更新electron版本,更新方式戳这里https://blog.csdn.net/weixin_43272648/article/details/104339699

 

第一步,安装electron-updater依赖

npm install electron-updater --save

 

第二步,配置package.json文件

在package.json中build配置项下边添加如下代码

"build": {
    ...

    "publish": [
      {
        "provider": "generic",
        "url": "http://localhost:8080/package" // 这里是存放.exe和latest.yml文件的地址
      }
    ],
    
    ...
}

 

第三步,新建更新文件

创建/src/main/model/update.js 文件,model这个文件夹初始是没有的,可以自己创建

/**
 * @description 执行自动更新检查
 * @author: hruomei
 * @update 暂无
 * @date: 2020-08-24 17:09:32
 */

const { ipcMain } = require('electron')
const { autoUpdater } = require("electron-updater")
const { build } = require("../../../package.json")

// 用户反馈立即更新
ipcMain.on('ev-update-now', () => {
    console.log('ev-update-now::: 用户同意更新,开始更新') 

    autoUpdater.quitAndInstall()
})

// 用户也可以通过点击按钮去检测更新
ipcMain.on('ev-check-for-update', () => {
    console.log('ev-check-for-update::: 执行自动更新检查') 

    autoUpdater.checkForUpdates()
})

function handleUpdate(mainWindow) {
    const message = {
        error: '检查更新出错',
        checking: '正在检查更新……',
        updateAva: '检测到新版本,正在下载……',
        updateNotAva: '现在使用的就是最新版本,不用更新'
    }

    autoUpdater.setFeedURL(build.publish[0].url) // 设置下载地址

    // 检查更新出错
    autoUpdater.on('error', () => {
        console.log('autoUpdater-error:::', arguments)

        sendUpdateMessage(message.error)
    })

    // 检查是否有版本更新
    autoUpdater.on('checking-for-update', () => {
        console.log('checking-for-update:::', arguments)

        sendUpdateMessage(message.checking)
    })

    // 检测到有版本更新
    autoUpdater.on('update-available', () => {
        console.log('update-available:::', arguments)

        sendUpdateMessage(message.updateAva)
    })

    // 未发现有新版本
    autoUpdater.on('update-not-available', () => {
        console.log('update-not-available:::', arguments)

        sendUpdateMessage(message.updateNotAva)
    })

    // 更新下载进度事件
    autoUpdater.on('download-progress', progressObj => {
        console.log('download-progress:::', progressObj)
        
        mainWindow.setProgressBar(progressObj.percent / 100)
    })

    // 下载完成,询问用户是否更新
    autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) => {
        console.log('update-downloaded::: 下载完成,询问用户是否更新') 
        
        mainWindow.webContents.send('ev-should-update', {
            event,
            releaseNotes,
            releaseName,
            releaseDate,
            updateUrl,
            quitAndUpdate
        })
    })

    function sendUpdateMessage(text) {
        mainWindow.webContents.send('ev-message', text)
    }
}

module.exports = {
    handleUpdate
}

代码位置如下

 

第四步,在主进程中引入update.js

在/src/main/index.js主进程文件中引入,并执行handleUpdate()

import {
    app,
    BrowserWindow,
    screen
} from 'electron'
const path = require('path')

const { handleUpdate } = require('./model/update')

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
    global.__static = path.join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development' ? `http://localhost:9080` : `file://${__dirname}/index.html`


function createWindow() {
    const size = screen.getPrimaryDisplay().workAreaSize
    const width = parseInt(size.width * 0.7)
    const height = parseInt(size.height * 0.9)

    mainWindow = new BrowserWindow({
        width,
        height,
        minWidth: 900,
        minHeight: 600,
        frame: false,
        useContentSize: true,
        autoHideMenuBar: true,
        webPreferences:{
            nodeIntegration: true // 在网页中集成Node
        }
    })

    mainWindow.loadURL(winURL)

    mainWindow.on('closed', () => {
        mainWindow = null
    })

    handleUpdate(mainWindow) // 在这里执行,并把mainWindow传入
}

// 单例应用
if (process.env.NODE_ENV === 'production') {
    const getTheLock = app.requestSingleInstanceLock()

    if (!getTheLock) {
        app.quit()
    } else {
        app.on('second-instance', (event, commandLine, workingDirectory) => {
            if (mainWindow) {
                if (mainWindow.isMinimized()) mainWindow.restore()
                mainWindow.focus()
            }
        })

        app.on('ready', createWindow)
    }
}

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow()
    }
})

 

第五步,在渲染进程中触发检测更新事件

/src/renderer/App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "App",

  mounted() {
    // 500毫秒延时避免渲染时卡顿
    setTimeout(() => {
      this.$electron.ipcRenderer.send('ev-check-for-update');
    }, 500);

    this.$electron.ipcRenderer.on("ev-message", (event, message) => {
      this.$notify({
        message,
        title: "提示",
      });
    });

    this.$electron.ipcRenderer.on("ev-should-update", (event, message) => {
      this.$confirm("检查到新版本,是否更新?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$electron.ipcRenderer.send("ev-update-now");
      });
    });
  },
};
</script>

<style>
/* CSS */
</style>

 

第六步,打包

首先,将package.json中的version改为0.0.1,执行npm run build打包,此时会生成0.0.1的.exe包和latest.yml文件。这是我们待会用来测试的包。

随后,将package.json中的version改为0.0.2,再执行npm run build打包,将打出的build文件夹下的0.0.2的.exe包和latest.yml文件拖到node服务的/public/package文件夹下

 

最后,测试

启动node服务

双击打开0.0.1版本的包,会提示正在“正在检查更新……”,然后弹出“检查到新版本,是否更新?”的提示,点击确定,即可更新

 

 

 

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值