electron-vue+electron-updater实现自动更新

创建一个electron+vue项目

https://blog.csdn.net/wudunkai/article/details/115130189?spm=1001.2014.3001.5501

依赖electron-updater

npm install electron-updater --save

创建vue.config.js

vue.config.js 是一个可选的配置文件,如果项目的 (和 package.json 同级的) 根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。你也可以使用 package.json 中的 vue 字段,但是注意这种写法需要你严格遵照 JSON 的格式来写。

在根目录中创建 vue.config.js
在这里插入图片描述

  1. 配置vue.config.js文件
module.exports = {
  pluginOptions: {
    electronBuilder: {
      builderOptions: {
        productName: 'demo',
        publish: [
          {
            provider: "generic",
            url: "http://xxxxxxx/download"
          }
        ],
      }
    },
  }
};

配置自动更新文件

1.创建文件electron-updater.js
在这里插入图片描述
2.配置electron-updater.js文件内容

import {
  autoUpdater
} from 'electron-updater'

import {
  ipcMain
} from 'electron'
let mainWindow = null;
export function updateHandle(window, feedUrl) {
  mainWindow = window;
  //设置更新包的地址
  autoUpdater.setFeedURL(feedUrl);
  //监听升级失败事件
  autoUpdater.on('error', function (error) {
    sendUpdateMessage({
      cmd: 'error',
      message: error
    })
  });
  //监听开始检测更新事件
  autoUpdater.on('checking-for-update', function (message) {
    sendUpdateMessage({
      cmd: 'checking-for-update',
      message: message
    })
  });
  //监听发现可用更新事件
  autoUpdater.on('update-available', function (message) {
    sendUpdateMessage({
      cmd: 'update-available',
      message: message
    })
  });
  //监听没有可用更新事件
  autoUpdater.on('update-not-available', function (message) {
    sendUpdateMessage({
      cmd: 'update-not-available',
      message: message
    })
  });

  // 更新下载进度事件
  autoUpdater.on('download-progress', function (progressObj) {
    sendUpdateMessage({
      cmd: 'download-progress',
      message: progressObj
    })
  });
  //监听下载完成事件
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl) {
    sendUpdateMessage({
      cmd: 'update-downloaded',
      message: {
        releaseNotes,
        releaseName,
        releaseDate,
        updateUrl
      }
    })
    //退出并安装更新包
    autoUpdater.quitAndInstall();
  });

  //接收渲染进程消息,开始检查更新
  ipcMain.on("checkForUpdate", () => {
    //执行自动更新检查
    // sendUpdateMessage({cmd:'checkForUpdate',message:arg})
    autoUpdater.checkForUpdates();
  })
}
//给渲染进程发送消息
function sendUpdateMessage(text) {
  mainWindow.webContents.send('message', text)
}

3.引入src/background.js文件

'use strict'

import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
//引入electron-updater文件
import { updateHandle } from '@/electron-updater.js';

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      // nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
      // 是提示可以为了版本前向兼容,可以控制是否集成node。方式是在Electron工程的main.js里,增加一段webPreferences:{nodeIntegration: true}的内容:
      nodeIntegration: true
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
  //调用方法
  updateHandle(win, 'http://xxxxxxxxx/download')
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

注:中文是引入的内容,主要是调用方法

  1. App.vue文件配置前端样式更新
<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App" />
  <el-dialog title="正在更新新版本,请稍候..." v-model="dialogVisible" width="60%" :close-on-click-modal="closeOnClickModal" :close-on-press-escape="closeOnPressEscape" :show-close="showClose" center>
    <div style="width:100%;height:20vh;line-height:20vh;text-align:center">
      <el-progress status="success" :text-inside="true" :stroke-width="20" :percentage="percentage" :width="strokeWidth" :show-text="true"></el-progress>
    </div>
  </el-dialog>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
const { ipcRenderer } = window.require("electron");
export default {
  name: 'App',
  data() {
    return {
      // 处理自动更新
      dialogVisible: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      showClose: false,
      percentage: 0,
      strokeWidth: 200,
    }
  },
  mounted() {
    let _this = this;
    //接收主进程版本更新消息
    ipcRenderer.on("message", (event, arg) => {
      // for (var i = 0; i < arg.length; i++) {
      if ("update-not-available" == arg.cmd) {
        // console.log(arg.message.version);
      }
      if ("update-available" == arg.cmd) {
        //显示升级对话框
        _this.dialogVisible = true;
      } else if ("download-progress" == arg.cmd) {
        //更新升级进度
        /**
        * 
        * message{bytesPerSecond: 47673
          delta: 48960
          percent: 0.11438799862426002
          total: 42801693
          transferred: 48960
          }
        */
        // console.log(arg.message.percent);
        let percent = Math.round(parseFloat(arg.message.percent));
        _this.percentage = percent;
      } else if ("error" == arg.cmd) {
        _this.dialogVisible = false;
        _this.$message("更新失败");
      }
      // }
    });
    ipcRenderer.send("checkForUpdate");
  },
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

注:这里使用了element-ui

npm add element-plus
  1. 打包项目
npm run electron:build
  1. 把文件发布服务器
    在这里插入图片描述
  2. 安装demo Setup 0.1.0.exe,将会实现自动更新
    在这里插入图片描述
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值