Advertisement

Electron开发跨平台桌面应用

阅读量:

尽管 B/S 已成为当前开发的主要方式,然而 C/S 仍存在较大的市场潜力.由于浏览器的安全机制限制,网页应用在某些特定场景下无法满足需求,而桌面应用则能够访问本地文件并利用更多的系统资源.并且得益于 Web 开发在成本和效率上的显著优势,这种跨平台开发模式正逐渐受到开发者青睐.
Electron 基于 Chromium 搭配 Node.js 构建而成,通过混合使用 HTML、CSS 和 JavaScript 技术来实现跨平台功能.它不仅支持 Mac、Windows 和 Linux 系统,还集成了包括 VScode 和 Atom 等众多工具,充分展现了其强大的适用性.

一、准备工作

在创建Electron跨平台应用之前,在线会被要求先预装一些必要的组件,并包括Node以及Electron

  1. 安装node在前说过就不详细说了。
  2. 安装Electron。
复制代码
 npm install -g electron

    
 // 或者
    
 cnpm install -g electron
    
 // 验证是否安装成功
    
 electron -v

二、创建项目

官方推出了一个简单的项目用于帮助用户克隆到本地环境中运行Electron应用程序

复制代码
    git clone https://github.com/electron/electron-quick-start
  1. 安装依赖
复制代码
 cd electron-quick-start

    
 npm install
  1. 运行
复制代码
    npm start

效果图

三、更改内容

在项目的启动后, 我们计划对项目进行一些修改, 以便执行所需的内容

  1. 放入静态文件
    在项目根目录新建static文件夹,将静态文件放入。

  2. 更改main.js

复制代码
 /* * @Description: 主入口文件
    
  * @Author: cuiht
    
  * @Date: 2021-01-13 15:58:29
    
  * @LastEditTime: 2021-01-14 15:04:16
    
  */
    
 // Modules to control application life and create native browser window
    
 const {
    
   app,
    
   globalShortcut,
    
   screen,
    
   dialog,
    
   BrowserWindow,
    
   Menu,
    
 } = require("electron");
    
 const path = require("path");
    
  
    
 function createWindow() {
    
   // 去除菜单栏
    
   Menu.setApplicationMenu(null);
    
   // 创建窗口
    
   const mainWindow = new BrowserWindow({
    
     width: screen.getPrimaryDisplay().workAreaSize.width * 0.9,
    
     height: screen.getPrimaryDisplay().workAreaSize.height * 0.9,
    
     fullscreen: true,
    
     webPreferences: {
    
       nodeIntegration: true,
    
       preload: path.join(__dirname, "preload.js"),
    
     },
    
   });
    
   // //配置ESC键退出全屏
    
   globalShortcut.register("ESC", () => {
    
     mainWindow.close();
    
   });
    
   // //配置F11切换全屏
    
   // globalShortcut.register("F11", () => {
    
   //   mainWindow.setFullScreen(!mainWindow.isFullScreen());
    
   // });
    
   // 加载静态文件
    
   mainWindow.loadFile("static/index.html");
    
   // 监听窗口关闭
    
   mainWindow.on("close", (e) => {
    
     e.preventDefault();
    
     dialog
    
       .showMessageBox({
    
     type: "info",
    
     title: "提示",
    
     defaultId: 0,
    
     message: "确定要退出吗?",
    
     buttons: ["最小化", "退出"],
    
       })
    
       .then((result) => {
    
     if (result.response === 0) {
    
       e.preventDefault();
    
       mainWindow.minimize();
    
     } else {
    
       app.exit(); //exit()直接关闭客户端,不会执行quit();
    
     }
    
       })
    
       .catch((err) => {
    
     console.log(err);
    
       });
    
   });
    
   // 监听程序崩溃
    
   mainWindow.webContents.on("crashed", () => {
    
     const options = {
    
       type: "error",
    
       title: "进程崩溃了",
    
       message: "这个进程已经崩溃.",
    
       buttons: ["重载", "退出"],
    
     };
    
     recordCrash()
    
       .then(() => {
    
     dialog
    
       .showMessageBox(options)
    
       .then((result) => {
    
         if (result.response === 0) {
    
           reloadWindow(mainWindow);
    
         } else {
    
           app.exit();
    
         }
    
       })
    
       .catch((err) => {
    
         console.log(err);
    
       });
    
       })
    
       .catch((e) => {
    
     console.log("err", e);
    
       });
    
   });
    
 }
    
 // 崩溃日志请求
    
 function recordCrash() {
    
   return new Promise((resolve) => {
    
     // 崩溃日志请求成功....
    
     resolve();
    
   });
    
 }
    
 // 重载窗口
    
 function reloadWindow(mainWin) {
    
   if (mainWin.isDestroyed()) {
    
     app.relaunch();
    
     app.exit(0);
    
   } else {
    
     BrowserWindow.getAllWindows().forEach((w) => {
    
       if (w.id !== mainWin.id) w.destroy();
    
     });
    
     mainWin.reload();
    
   }
    
 }
    
  
    
 // 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.whenReady().then(() => {
    
   createWindow();
    
   app.on("activate", function () {
    
     // 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();
    
   });
    
 });
    
   124. // Quit when all windows are closed, except on macOS. There, it's common
    
 // for applications and their menu bar to stay active until the user quits
    
 // explicitly with Cmd + Q.
    
 app.on("window-all-closed", function () {
    
   if (process.platform !== "darwin") app.quit();
    
   // 注销所有快捷键
    
   globalShortcut.unregisterAll();
    
 });
    
  
    
 // In this file you can include the rest of your app's specific main process
    
 // code. You can also put them in separate files and require them here.
    
    
    
    
    AI写代码
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-06-01/tcDSai1EfMPT94Hw3BXxdbAzjkCU.png)

目录

四、打包为exe文件

  1. 安装打包工具electron-packager
复制代码
    cnpm install electron-packager -g
  1. 打包
    在项目根目录运行
复制代码
    electron-packager . HelloWorld --platform=win32 --arch=x64 --icon=computer.ico --out=./out --asar --app-version=0.0.1 --overwrite --ignore=node_modules --electron-version 5.0.0

各个参数介绍:
HelloWorld :你将要生成的exe文件的名称
--platform=win32:确定了你要构建哪个平台的应用,可取的值有 darwin, linux, mac, win32
--arch=x64:决定了使用 x86 还是 x64 还是两个架构都用
--icon=computer.ico:自定义设置应用图标
--out=./out:指定打包文件输出的文件夹位置,当前指定的为项目目录下的out文件夹
--asar:该参数可以不加,如果加上,打包之后应用的源码会以.asar格式存在,否则会以文件夹形式存在
--app-version=0.0.1:生成应用的版本号
--overwrite:覆盖原有的build,让新生成的包覆盖原来的包
--ignore=node_modules:如果加上该参数,项目里node_modules模块不会被打包进去
--electron-version 5.0.0:指定当前要构建的electron的版本,需要和当前的版本一致,具体可以在package.json文件中查看,可以不加该参数,如果不一致,会自动下载,不建议设置

  1. 注意事项
    可以将打包命令写入 package.json中方便后续开发。
    eg:
复制代码
 "scripts": {

    
     "start": "electron .",
    
     "package": "electron-packager . HelloWorld --platform=win32 --arch=x64 --icon=computer.ico --out=./out --asar --app-version=0.0.1 --overwrite --ignore=node_modules"
    
   },

发现,在尝试下载electron-v1.8.3-win32-x64.zip的时候(注意:此处应有适当空格),如果遇到等待时间过长且无网络的情况(注意:此处应有适当标点),是因为该压缩包由国外服务器提供而导致网络速度缓慢且不稳定(注意:此处应有适当标点)。因此,在开始下载之前,请将镜像地址更换为来自淘宝的服务端。

复制代码
>     npm config set ELECTRON_MIRROR https://npm.taobao.org/mirrors/electron/
>  
>     AI写代码javascript
>  
>     运行

然后运行

复制代码
    npm run package

当在打包过程中遇到下载文件的提示时

打包成功
打包后会生成如下文件夹,点击运行HelloWorld.exe,就可以了。

文件目录

效果图

效果图

参考文献:electronjs
世界的模样,则由你审视的目光所决定;
自己的价值,则由你的追求态度和精神状态所决定;
一切美好的愿望,则是在奋斗中争取!

全部评论 (0)

还没有任何评论哟~