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

news/2024/9/15 0:12:27 标签: electron, javascript, 前端

技术选型

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

参考文献

更多

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

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


http://www.niftyadmin.cn/n/5632107.html

相关文章

vue中引入全局css

在app.vue中引入 import Vue from vue; import App from ./App.vue; import ./assets/global.css; // 全局CSS文件new Vue({render: h > h(App), }).$mount(#app);

【日常记录-JS】HTML5中使用SVG元素

Author&#xff1a;赵志乾 Date&#xff1a;2024-08-28 Declaration&#xff1a;All Right Reserved&#xff01;&#xff01;&#xff01; 1. 简介 在HTML5中使用SVG元素主要涉及到将SVG代码直接嵌入HTML文档&#xff0c;或者通过HTML元素&#xff08;如<img>、<obj…

搭建数据库启前后端环境

1、 安装postgre&#xff0c;修改pg_hba.conf文件 2、安装dbeaer 3、任务管理器-服务&#xff1a;查看是否启动postgresql-x64-11 4、连接测试&#xff1a;新建数据库连接 http://127.0.0.1:14269/browser/# pgAdmin等于dbeaver 5、创建数据库&#xff1a; 6、启动后端…

基于RAG多层次的多代理架构来处理时序任务

《Agentic Retrieval-Augmented Generation for Time Series Analysis》这篇文章提出了一种新颖的时间序列分析方法&#xff0c;称为Agentic Retrieval-Augmented Generation&#xff08;RAG&#xff09;框架。它通过多层次的多代理架构来处理时间序列任务&#xff0c;其中主代…

《NLP自然语言处理》—— 关键字提取之TF-IDF算法

文章目录 一、TF-IDF算法介绍二、举例说明三、示例&#xff1a;代码实现四、总结 一、TF-IDF算法介绍 TF-IDF&#xff08;Term Frequency-Inverse Document Frequency&#xff09;是一种用于信息检索与文本挖掘的常用加权技术。TF-IDF是一种统计方法&#xff0c;用以评估一个词…

vue3项目使用EventSource实现流式输出例如滚动日志

前言 之前接触的通信方式主要是HTTP请求和WebSocket&#xff0c;这次有机会了解到EventSource&#xff0c;记录一下。 简介 EventSource是一个浏览器端用于接收服务器推送事件&#xff08;Server-Sent Events, SSE&#xff09;的 JS API。与 WebSocket 不同&#xff0c;SSE …

docker仓库的工作原理

仓库中的三个角色 index docker 索引服务&#xff0c;负责并维护有关用户帐户、镜像的校验以及公共命名空间的信息。 registry docker 仓库&#xff0c;是镜像和图表的仓库&#xff0c;它不具有本地数据库以及不提供用户认证&#xff0c;通过 Index Auth service 的 Token 的…

AIGC提示词(3):AI的创造力之谜:相同提示词,不同内容

引言 在这个数字化的时代&#xff0c;人工智能生成内容&#xff08;AIGC&#xff09;已经变得无处不在。想象一下&#xff0c;只需输入几个关键词&#xff0c;AI就能创作出各种内容&#xff0c;无论是文字、图片&#xff0c;还是其他形式。但这里有个有趣的问题&#xff1a;如…