当前位置: 首页 > news >正文

Electron 项目实战 02:打包和自动更新

技术选型

  • electron-forge
  • electron-builder

electron-forge 是Electron 官方文档介绍的,打包和发布都包含了,但是包含的坑也非常多。electron-builder下载量和集成打包非常顺利,本教程也是采用electron-buid来介绍打包。大家在技术选型的时候要多找几个,原则:选下载量高、社区活跃度高、问题少的技术,这样可以让你少走很多弯路。

由于我没有mac os 环境,就只介绍windows 环境打包和更新,按文档添加对应配置应该问题不大。

安装依赖

yarn add electron-builder -D

添加打包配置

  • package.json

    {"name": "my-electron-app","version": "0.0.1","main": "main.js","author": "Potter<aa4790139@gmail.com>","license": "MIT","scripts": {"dev": "electron .","publish": "electron-builder --win -p always"},"build": {"appId": "com.my.electron.app","productName": "my-electron-app","publish": [{"provider": "github","owner": "yxw007","repo": "electron_app"}],"win": {"target": "nsis"},"directories": {"output": "build"},"nsis": {"oneClick": false,"allowToChangeInstallationDirectory": true}},"devDependencies": {"electron": "^28.0.0","electron-builder": "^24.9.1"},
    }
    

打包

npm run publish

Untitled.png

打包后会自动发布至github对应仓库,Release页会自动生成一个Draft,需要手动发布才能成为正式版本

Untitled 1.png

集成自动更新

  • 安装依赖

    yarn add electron-updater electron-log
    
  • index.html,添加一个更新标签来显示我们的更新信息

    <!DOCTYPE html>
    <html><head><meta charset="UTF-8" /><!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --><meta http-equiv="Content-Security-Policy"content="default-src 'self'; script-src 'self'" /><meta http-equiv="X-Content-Security-Policy"content="default-src 'self'; script-src 'self'" /><title>Electron App</title>
    </head><body><div>Electron App</div>Current version: <span id="version">vX.Y.Z</span><p id="info"></p><div id="message"></div>
    </body>
    <script src="./renderer.js"></script></html>
    
  • main.js 添加自动相关代码

    const { app, BrowserWindow, ipcMain } = require("electron");
    const path = require("node:path");
    //1.添加日志显示,方便问题排查
    const log = require("electron-log");
    const { autoUpdater } = require("electron-updater");autoUpdater.logger = log;
    autoUpdater.logger.transports.file.level = "info";
    log.info("App starting...");let win;
    const createWindow = () => {win = new BrowserWindow({width: 800,height: 600,webPreferences: {preload: path.join(__dirname, "preload.js"),},});// win.loadFile("index.html");win.loadURL(`file://${__dirname}/index.html#v${app.getVersion()}`);
    };function sendStatusToWindow(text) {log.info(text);win.webContents.send("message", { message: text });
    }
    //! autoUpdater 监听相关的常用事件
    autoUpdater.on("checking-for-update", () => {sendStatusToWindow("Checking for update...");
    });
    autoUpdater.on("update-available", (info) => {sendStatusToWindow("Update available.");
    });
    autoUpdater.on("update-not-available", (info) => {sendStatusToWindow("Update not available.");
    });
    autoUpdater.on("error", (err) => {sendStatusToWindow("Error in auto-updater. " + err);
    });
    autoUpdater.on("download-progress", (progressObj) => {let log_message = "Download speed: " + progressObj.bytesPerSecond;log_message = log_message + " - Downloaded " + progressObj.percent + "%";log_message =log_message +" (" +progressObj.transferred +"/" +progressObj.total +")";sendStatusToWindow(log_message);
    });
    autoUpdater.on("update-downloaded", (info) => {sendStatusToWindow("Update downloaded");//! 下载完后立即更新autoUpdater.quitAndInstall();
    });app.whenReady().then(() => {//! 主进程,处理渲染进程的消息ipcMain.handle("ping", () => {return `I'm ipcMain`;});// ! 1.监听来自渲染进程的消息ipcMain.on("message-from-renderer", (event, arg) => {console.log("Renderer Process Message:", arg);//! 2.发送回复消息到渲染进程event.sender.send("message-from-main", "Hello from main process!");});createWindow();console.log(process.platform);app.on("activate", () => {if (BrowserWindow.getAllWindows().length === 0) {createWindow();}});
    });app.whenReady().then(() => {//! app ready 自动检查更新autoUpdater.checkForUpdatesAndNotify();console.log("app ready: checkForUpdatesAndNotify");
    });app.on("window-all-closed", () => {if (process.platform !== "darwin") {console.log("quit");app.quit();}
    });
    

重新发布版本

npm run publish

此时github 对应仓库Release 页面又会多一个Draft版本,点击修改让其发布,然后更新package.json 中的版本号,再重新发布一次。

为了让你看到这个过程,你可以先下载我演示的my-electron-app-Setup-0.1.4.exe,安装完后打开会检测自动更新,安装完后再打开就会看到更新至v0.1.5

Untitled 2.png

Untitled 3.png

总结

  • 技术选型时尽量多选几个,选择下载量高、社区活跃高(发包更新频率、bug修复数量、bug修复速度综合对比下)的技术,可以让你少踩坑

补充

说明:如果更新出错,可以到C:\Users\Administrator\AppData\Roaming\xxx\logs 目录下查看main.log 日志查看具体问题

完整:demo

参考文献

  • https://github.com/yxw007/electron-updater-example
  • https://www.electron.build/

更多

家人们,我最近花了2个多月开源了一个文章发布助手artipub,可以帮你一键将markdown发布至多平台(发布和更新),方便大家更好的传播知识和分享你的经验。
目前已支持平台:个人博客、Medium、Dev.to(未来会支持更多平台)
官网地址:https://artipub.github.io/artipub/
仓库地址:https://github.com/artipub/artipub

目前库已可以正常使用,欢迎大家体验、如果你有任何问题和建议都可以提Issue给我反馈。
如果你感兴趣,特别欢迎你的加入,让我们一起完善好这个工具。
帮忙点个star⭐,让更多人知道这个工具,感谢大家🙏

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 有temp表包含A,B两列,使用SQL,对B列进行处理,形成C列,按A列顺序,B列值不变,则C列累计技术,B列值变化,则C列重新开始计数
  • 数据库课程设计mysql---图书管理系统详细的设计文档和需求文档
  • TCP如何关闭连接(详细版)
  • 如何进行 AWS 云监控
  • Meta关闭Spark AR平台:未来规划与影响分析
  • 内存分配算法
  • SpringBoot实现前后端传输加密设计
  • Elasticsearch 基本语法使用
  • 排除挖矿木马
  • Node.js 异步编程深度解析:回调函数、Promise 以及 async/await
  • Vue3 使用 富文本编辑器 wangeditor/editor-for-vue 配置详解
  • MySQL之SUBSTRING 和 SUBSTRING_INDEX函数
  • 个人手机发短信和106短信群发平台的本质区别是什么?
  • 【开发实战】QT5 + 深度学习六大应用案例
  • PCL 移动立方体三维重建——RBF算法【2024最新版】
  • 【159天】尚学堂高琪Java300集视频精华笔记(128)
  • 【JavaScript】通过闭包创建具有私有属性的实例对象
  • 【Under-the-hood-ReactJS-Part0】React源码解读
  • 30天自制操作系统-2
  • CentOS 7 修改主机名
  • codis proxy处理流程
  • CSS选择器——伪元素选择器之处理父元素高度及外边距溢出
  • idea + plantuml 画流程图
  • Java反射-动态类加载和重新加载
  • Laravel5.4 Queues队列学习
  • Traffic-Sign Detection and Classification in the Wild 论文笔记
  • vue+element后台管理系统,从后端获取路由表,并正常渲染
  • vue从入门到进阶:计算属性computed与侦听器watch(三)
  • vue中实现单选
  • XForms - 更强大的Form
  • 安装python包到指定虚拟环境
  • 二维平面内的碰撞检测【一】
  • 干货 | 以太坊Mist负责人教你建立无服务器应用
  • 容器化应用: 在阿里云搭建多节点 Openshift 集群
  • 设计模式 开闭原则
  • 深度学习在携程攻略社区的应用
  • 使用 QuickBI 搭建酷炫可视化分析
  • 微信小程序:实现悬浮返回和分享按钮
  • 正则表达式
  • MiKTeX could not find the script engine ‘perl.exe‘ which is required to execute ‘latexmk‘.
  • ​草莓熊python turtle绘图代码(玫瑰花版)附源代码
  • ​经​纬​恒​润​二​面​​三​七​互​娱​一​面​​元​象​二​面​
  • (2)关于RabbitMq 的 Topic Exchange 主题交换机
  • (2024,RWKV-5/6,RNN,矩阵值注意力状态,数据依赖线性插值,LoRA,多语言分词器)Eagle 和 Finch
  • (35)远程识别(又称无人机识别)(二)
  • (a /b)*c的值
  • (LLM) 很笨
  • (Matalb分类预测)GA-BP遗传算法优化BP神经网络的多维分类预测
  • (办公)springboot配置aop处理请求.
  • (附源码)python旅游推荐系统 毕业设计 250623
  • (附源码)计算机毕业设计ssm-Java网名推荐系统
  • (四)activit5.23.0修复跟踪高亮显示BUG
  • (图文详解)小程序AppID申请以及在Hbuilderx中运行
  • (推荐)叮当——中文语音对话机器人
  • (转)http协议