Vue2+electron开发桌面端应用并实现自动更新

本文详细介绍了如何使用Vue和Electron开发项目,包括安装Electron、使用electron-builder打包工具、集成electron-updater实现自动更新功能,以及自定义安装路径和处理常见问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.新建项目

vue create demo

2.安装electron

yarn add electron

3.添加打包工具

vue add electron-builder
安装后 src 下会生成 background.js 文件,package.json 也会生成对应的命令并把 background.js 作为入口文件

4.自动更新

  • 安装依赖 electron-updater
  • 自定义更新的文件 handleUpdate.js 在src 目录下
  • 本地调试检测更新时要 修改 autoUpdater.updateConfigPath
  • 打包完会生成一个latest.yml文件,把这个文件和生成的.exe文件放在服务器上,会自动检测版本
  • 新版本号要大于老版本号才会触发更新
//handleUpdate.js
import {
	autoUpdater
} from 'electron-updater'

import {
	ipcMain,dialog
} from 'electron'
const path = require("path")
let mainWindow = null;
// autoUpdater.updateConfigPath = path.join(__filename, '../win-unpacked/resources/app-update.yml')本地测试更新版本时修改下地址
console.log(__filename)

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

`autoUpdater.autoDownload = false;` //取消自动下载
	//设置更新包的地址
    // autoUpdater.currentVersion = "0.1.1"
	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("quit-install", (e, arg) => {
		autoUpdater.quitAndInstall();
	})
	//接收渲染进程消息,开始检查更新
	ipcMain.on("checkForUpdate", (e, arg) => {
		//执行自动更新检查
		// sendUpdateMessage({cmd:'checkForUpdate',message:arg})
        console.log(arg)
		autoUpdater.checkForUpdates();
	})
}
//给渲染进程发送消息
function sendUpdateMessage(text) {
	mainWindow.webContents.send('message', text)
}

5.在主进程文件background.js里面引用 handleUpdate.js

  • 引入文件
const {
	handleUpdate
} = require('./handleUpdate.js') //根据自己路径引入 我是跟background.js同级放的`
  • 在 createWindow 函数底部调用检测更新函数,第二个参数为 “.exe文件存放路径” (服务器上存放.exe文件的目录路径)
//检查更新
handleUpdate(win, "http://127.0.0.1:5502")

6.自定义安装路径

打包安装默认是直接装在c盘的
新建vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  pluginOptions: {
    electronBuilder: {
        chainWebpackMainProcess: (config) => {
            config.output.filename('background.js');
        },
        nodeIntegration: true,
        builderOptions: {
          nsis: {
            allowToChangeInstallationDirectory: true, //自定义安装路径
            oneClick: false,
          },
          win: {
            publish: [{
              provider: "generic",
              url: "http://127.0.0.1:5502"  //更新包地址  
            }],
          },
          productName: 'electronDemo'  //项目名(应用名)
        }
    }
}
})

7.自动检测更新

在App.vue添加检测代码:

let ipcRenderer = require("electron").ipcRenderer;

mounted(){

    let _this = this;
			//新增 
			this.timer = setInterval(() => {
				setTimeout(() => {
					ipcRenderer.send("checkForUpdate");
				}, 1)
			},10000)

			//接收主进程版本更新消息
			ipcRenderer.on("message", (event, arg) => {
				if ("update-downloaded" == arg.cmd) {
					_this.$alert('新版本已经下载完成', '提示信息', {
						confirmButtonText: '立即安装',
						callback: () => {
							ipcRenderer.send("quit-install")
						}
					});
				}
			});

  }

8.常见报错:

  1. (node:24312) [DEP0128] DeprecationWarning: Invalid ‘main’ field in ‘C:\xxx\dist_electron\package.json’ of ‘background.js’. Please either fix that or report it to the module author
    (Use electron --trace-deprecation … to show where the warning was created)

解决办法:
以上是在说同级目录有index.js文件存在,需要更改electron主进程文件名。 在开发过程中,dist_electron目录会生成两个文件:index.js和package.json,冲突就在这个文件夹,所以只需要把index.js文件名修改成background.js就可以了
在vue.config.js

 pluginOptions: {
    electronBuilder: {
        chainWebpackMainProcess: (config) => {
            config.output.filename('background.js');
        }
    }
}

2.路由访问出错
解决方法:
electron生成的路径会带有磁盘的盘符,所以在布局组件返回的路径应该这么写:

return path.posix.resolve(this.basePath, routePath)

原来的是:return path.resolve(this.basePath, routePath)

3.electron 使用js-cookie 设置cookie无效,建议使用localstorage

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值