当前位置: 代码迷 >> 综合 >> Vue+Electron学习系列 (三) -- 自动更新
  详细解决方案

Vue+Electron学习系列 (三) -- 自动更新

热度:89   发布时间:2024-02-19 21:08:05.0

electron+vue打包后自动检测版本并更新

前提(默认已安装如下扩展):

    vue:3.0.0-rc.12

    electron: 10.1.1

    electron-updater: 4.3.4

配置文件设置

// vue.config.js 默认无此文件,可自行在根目录下创建
module.exports = {//vue配置publicPath: process.env.NODE_ENV ==='production' ? './' : '/',pluginOptions: {electronBuilder: {builderOptions: {...//此处省略打包配置参数...//发布更新//增加此配置主要是打包时可生成latest.yml文件publish: [{provider: "generic",url: "http://localhost/releases/"          }]}}}
};

仅需在主进程监听即可(上代码)

// 主进程 background.js
// 注意此处使用electron-log
'use strict'import { app, protocol, Menu, BrowserWindow, ipcMain } 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'
const log = require('electron-log');
const { autoUpdater } = require("electron-updater")//-------------------------------------------------------------------
// Logging
// +++ 此处为新增
// THIS SECTION IS NOT REQUIRED
//
// This logging setup is not required for auto-updates to work,
// but it sure makes debugging easier :)
//-------------------------------------------------------------------
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');//-------------------------------------------------------------------
// Define the menu
// +++ 此处为新增
// THIS SECTION IS NOT REQUIRED
//-------------------------------------------------------------------
let template = []// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let winfunction sendStatusToWindow(text) {log.info(text);win.webContents.send('message', text);
}// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }
])function createWindow() {// Create the browser window.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 infonodeIntegration: process.env.ELECTRON_NODE_INTEGRATION},icon: `${__static}/icon.png`})if (process.env.WEBPACK_DEV_SERVER_URL) {// Load the url of the dev server if in development modewin.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 developmentwin.loadURL('app://./index.html')}// 检测更新// +++ 此处为新增 -- startautoUpdater.checkForUpdatesAndNotify()// +++ 此处为新增 -- endwin.on('closed', () => {win = null})
}// 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 + Qif (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 (win === null) {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 Devtoolstry {await installExtension(VUEJS_DEVTOOLS)} catch (e) {console.error('Vue Devtools failed to install:', e.toString())}}// +++ 此处为新增 -- start// Create the Menuconst menu = Menu.buildFromTemplate(template);Menu.setApplicationMenu(menu);// +++ 此处为新增 -- endcreateWindow()
})// 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()})}
}// +++ 此处为新增 -- start
//自动更新事件监听
autoUpdater.on('checking-for-update', () => {sendStatusToWindow('Checking for update...');
})
autoUpdater.on('update-available', (ev, info) => {sendStatusToWindow('Update available.');
})
autoUpdater.on('update-not-available', (ev, info) => {sendStatusToWindow('Update not available.');
})
autoUpdater.on('error', (ev, err) => {sendStatusToWindow('Error in auto-updater.');
})
autoUpdater.on('download-progress', (ev, progressObj) => {sendStatusToWindow('Download progress...');
})
autoUpdater.on('update-downloaded', (ev, info) => {sendStatusToWindow('Update downloaded; will install in 5 seconds');
});
// 下载完成后等候5s退出并更新安装
autoUpdater.on('update-downloaded', (ev, info) => {setTimeout(function() {autoUpdater.quitAndInstall();  }, 5000)
})
// 应用启动后执行自动更新
app.on('ready', function() {autoUpdater.checkForUpdates();
})
// +++ 此处为新增 -- end

注意:仅需将打包后的程序:xxx.exe、xxx.exeblockmap、latest,yml上传至配置好的更新目录地址下即可

 

 

  相关解决方案