使用Electron构建跨平台的桌面应用程序(一)快速入门

我正在参与CSDN《新程序员》有奖征文,活动链接:https://marketing.csdn.net/p/52c37904f6e1b69dc392234fff425442

 Electron
现在很多平台的软件都开始使用electron来构建和开发,比如 Visual Studio Code阿里云盘,下面是两个软件的包文件:

在这里插入图片描述在这里插入图片描述
Visual Studio Code 包文件阿里云盘 包文件

基于求实和学习的态度,于是自己也通过官网来认识和学习这个框架,或许以后有机会自己会用此框架开发一个桌面工具类的应用,方便自己使用。

一、介绍

Electron使用 JavaScript,HTML 和 CSS 构建跨平台的桌面应用程序。

electron

1、核心团队和贡献者

Electron 由 GitHub 的一个团队进行维护,包括社区中的一些活跃的贡献者。其中一些贡献者是独立开发者,也有一些就职于使用 Electron 进行开发的大型公司。我们很乐意增加新的活跃贡献者到项目的维护者中。阅读 如何成为 Electron 的贡献者

2、Electron 历史

Electron 历史中的里程碑:
2013年4月 Atom Shell 项目开始
2014年5月 Atom Shell 开源
2015年4月 Atom Shell 更名为 Electron
2016年5月 Electron 发布 v1.0.0
2016年5月 Electron 应用兼容 Mac App Store
2016年8月 Window Store 支持 Electron 应用

二、快速入门

1、前提环境

在使用Electron进行开发之前,您需要安装 Node.js。 建议您使用最新的LTS版本。

要检查 Node.js 是否正确安装,请在您的终端输入以下命令:

node -v
npm -v

这两个命令应输出了 Node.js 和 npm 的版本信息。我使用的版本信息如下:
 版本信息

注意:为了防止后续使用npm安装各种包的问题,可以先把安装源修改cnpm

cnpm 是 淘宝团队做的国内镜像,因为npm的服务器位于国外可能会影响安装。淘宝镜像与官方同步频率目前为 10分钟 一次以保证尽量与官方服务同步。

安装:命令提示符执行:

npm install cnpm -g --registry=https://registry.npm.taobao.org

cnpm -v 来测试是否成功安装

cnpm -v 

我的cnpm 版本信息如下:
在这里插入图片描述

以下很多情况下都是使用 cnpm 来执行安装。

2、创建你的应用程序

(1)、使用脚手架创建

Electron 应用程序遵循与其他 Node.js 项目相同的结构。 首先创建一个文件夹并初始化 npm 包。

mkdir my-electron-app && cd my-electron-app
npm init 或 cnpm init

init初始化命令会提示您在项目初始化配置中设置一些值 ,有几条规则需要遵循:

entry point 应为 main.js.
authordescription 可为任意值,但对于应用打包是必填项

以下是我的执行结果:
在这里插入图片描述
上面的截图最后就是自己的package.json文件内容。

然后,将 electron 包安装到应用的开发依赖中。

npm install --save-dev electron 或 cnpm install --save-dev electron

以下是执行结果:

$ cnpm install --save-dev electron
✔ Installed 1 packages
✔ Linked 81 latest versions
[1/2] scripts.postinstall electron@13.1.4 › @electron/get@1.12.4 › global-agent@2.2.0 › core-js@^3.6.5 run "node -e \"try{require('./postinstall')}catch(e){}\"", root: "/Users/sunct/work/my-electron-app/node_modules/_core-js@3.15.1@core-js"
Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
> https://opencollective.com/core-js 
> https://www.patreon.com/zloirock 

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

[1/2] scripts.postinstall electron@13.1.4 › @electron/get@1.12.4 › global-agent@2.2.0 › core-js@^3.6.5 finished in 59ms
[2/2] scripts.postinstall electron@* run "node install.js", root: "/Users/sunct/work/my-electron-app/node_modules/_electron@13.1.4@electron"
[2/2] scripts.postinstall electron@* finished in 2s
✔ Run 2 scripts
Recently updated (since 2021-06-18): 3 packages (detail see file /Users/sunct/work/my-electron-app/node_modules/.recently_updates.txt)
✔ All packages installed (87 packages installed from npm registry, used 3s(network 1s), speed 193.02kB/s, json 82(271kB), tarball 0B)

执行结果截图如下:
 electron

最后,要想能够执行 Electron ,在你的 package.json配置文件中的scripts字段下增加一条start命令:

"start": "electron ."

如图所示:
start

start命令能让您在开发模式下打开您的应用

npm start 或 cnpm start

注意:此脚本将告诉 Electron 在您项目根目录运行 此时,您的应用将立即抛出一个错误提示您它无法找到要运行的应用

报错信息如图所示:
报错信息

(2)、主进程文件

任何 Electron 应用程序的入口都是 main 文件。
这个文件控制了主进程,它运行在一个完整的Node.js环境中,负责控制您应用的生命周期,显示原生界面,执行特殊操作并管理渲染器进程。

执行期间,Electron 将依据应用中 package.json配置下main字段中配置的值查找此文件,我们在开始填写参数entry point 的时我们已设置为 main.js

要初始化这个main文件,需要在您项目的根目录下创建一个名为main.js的空文件。

注意:如果您此时再次运行start命令,您的应用将不再抛出任何错误! 然而,它不会做任何事因为我们还没有在main.js中添加任何代码。

为了快速看到效果,我们使用官方代码示例,我的`main.js 文件内容如下:

/*
 * @Author: your name
 * @Date: 2021-06-25 15:16:41
 * @LastEditTime: 2021-06-25 15:16:53
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: /my-electron-app/main.js
 */
// main.js

// Modules to control application life and create native browser window
// 导入作为公共JS模块:
const { app, BrowserWindow } = require('electron')
// 在文件头部引入 Node.js 中的 path 模块
const path = require('path')
// 添加一个createWindow()方法来将index.html加载进一个新的BrowserWindow实例
function createWindow () {
  // Create the browser window.
  // 修改现有的 createWindow() 函数
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// 部分 API 在 ready 事件触发后才能使用。
// 在 Electron 中,只有在 app 模块的 ready 事件被激发后才能创建浏览器窗口。 您可以通过使用 app.whenReady() API来监听此事件。 在whenReady()成功后调用createWindow()

app.whenReady().then(() => {
  createWindow()
	// 如果没有窗口打开则打开一个窗口 (macOS)
	// 当 Linux 和 Windows 应用在没有窗口打开时退出了,macOS 应用通常即使在没有打开任何窗口的情况下也继续运行,并且在没有窗口可用的情况下激活应用时会打开新的窗口。
	// 为了实现这一特性,监听 app 模块的 activate 事件,并在没有浏览器窗口打开的情况下调用你仅存的 createWindow() 方法。
	// 因为窗口无法在 ready 事件前创建,你应当在你的应用初始化后仅监听 activate 事件。 通过在您现有的 whenReady() 回调中附上您的事件监听器来完成这个操作。
  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()
  })
})

// 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.
// 关闭所有窗口时退出应用 (Windows & Linux)
// 在Windows和Linux上,关闭所有窗口通常会完全退出一个应用程序。
// 为了实现这一点,监听 app 模块的 'window-all-closed' 事件,并在用户不是在 macOS (darwin) 上运行时调用 [app.quit()][app-quit]
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. 也可以拆分成几个文件,然后用 require 导入。

说明:多读一下上面文件里的注释。

(3)、通过预加载脚本从渲染器访问Node.js

现在,要做的是输出Electron的版本号和它的依赖项到你的web页面上。

在主进程通过Node的全局 process 对象访问这个信息是微不足道的。 然而,你不能直接在主进程中编辑DOM,因为它无法访问渲染器 文档 上下文。 它们存在于完全不同的进程!

注意:如果您需要更深入地查看Electron进程,请先参阅官方 进程模型 文档。

这是将 预加载 脚本连接到渲染器时派上用场的地方。 预加载脚本在渲染器进程加载之前加载,并有权访问两个 渲染器全局 (例如 window 和 document) 和 Node.js 环境。

创建一个名为 preload.js 的新脚本如下:
我的 preload.js文件内容如下:

// preload.js

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector, text) => {
      const element = document.getElementById(selector)
      if (element) element.innerText = text
    }
  
    for (const dependency of ['chrome', 'node', 'electron']) {
      replaceText(`${dependency}-version`, process.versions[dependency])
    }
  })
  

上面的代码访问 Node.js process.versions 对象,并运行一个基本的 replaceText 辅助函数将版本号插入到 HTML 文档中。

要将此脚本附加到渲染器流程,请在你现有的 BrowserWindow 构造器中将路径中的预加载脚本传入 webPreferences.preload 选项。

(4)、创建页面

在我们的应用创建窗口前,我们需要先创建加载进该窗口的内容。 在 Electron 中,每个窗口中无论是本地的HTML文件还是远程URL都可以被加载显示。

官方手册中,采用本地HTML的方式。 我们在项目根目录下创建一个名为index.html的文件。

我的index.html文件内容如下:

<!--
 * @Author: your name
 * @Date: 2021-06-25 15:17:01
 * @LastEditTime: 2021-06-25 15:17:11
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: /my-electron-app/index.html
-->
<!--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>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.

    <!-- You can also require other files to run in this process -->
    <script src="./renderer.js"></script>
  </body>
</html>

此时如果你再运行 cnpm startnpm start
再运行

结果会弹出一个窗口,如下:

在这里插入图片描述
和一个程序坞图标
程序坞图标

3、打包并分发您的应用程序

最快捷的打包方式是使用 Electron Forge

(1)、使用Electron Forge打包

将 Electron Forge 添加到您应用的开发依赖中,并使用其"import"命令设置 Forge 的脚手架

   npm install --save-dev @electron-forge/cli 或 cnpm install --save-dev @electron-forge/cli

我的运行结果如下:

$ cnpm install --save-dev @electron-forge/cli
✔ Installed 1 packages
✔ Linked 338 latest versions
[1/1] scripts.install @electron-forge/cli@6.0.0-beta.57 › @electron-forge/shared-types@6.0.0-beta.57 › electron-rebuild@2.3.5 › lzma-native@^6.0.1 run "node-pre-gyp install --fallback-to-build && rimraf build", root: "/Users/sunct/work/my-electron-app/node_modules/_lzma-native@6.0.1@lzma-native"
node-pre-gyp WARN Using request for node-pre-gyp https download 
node-pre-gyp http GET https://node-pre-gyp.addaleax.net/lzma-native/lzma_native-v6.0.1-n-api-darwin-x64.tar.gz
node-pre-gyp http 200 https://node-pre-gyp.addaleax.net/lzma-native/lzma_native-v6.0.1-n-api-darwin-x64.tar.gz
[lzma-native] Success: "/Users/sunct/work/my-electron-app/node_modules/_lzma-native@6.0.1@lzma-native/binding-v6.0.1-n-api-darwin-x64/lzma_native.node" is installed via remote
[1/1] scripts.install @electron-forge/cli@6.0.0-beta.57 › @electron-forge/shared-types@6.0.0-beta.57 › electron-rebuild@2.3.5 › lzma-native@^6.0.1 finished in 3s
✔ Run 1 scripts
deprecate @electron-forge/cli@6.0.0-beta.57 › @electron-forge/shared-types@6.0.0-beta.57 › electron-rebuild@2.3.5 › lzma-native@6.0.1 › node-pre-gyp@^0.11.0 Please upgrade to @mapbox/node-pre-gyp: the non-scoped node-pre-gyp package is deprecated and only the @mapbox scoped package will recieve updates in the future
deprecate @electron-forge/cli@6.0.0-beta.57 › @electron-forge/shared-types@6.0.0-beta.57 › electron-rebuild@2.3.5 › node-gyp@7.1.2 › request@^2.88.2 request has been deprecated, see https://github.com/request/request/issues/3142
deprecate @electron-forge/cli@6.0.0-beta.57 › @electron-forge/shared-types@6.0.0-beta.57 › electron-rebuild@2.3.5 › node-gyp@7.1.2 › request@2.88.2 › har-validator@~5.1.3 this library is no longer supported
Recently updated (since 2021-06-18): 3 packages (detail see file /Users/sunct/work/my-electron-app/node_modules/.recently_updates.txt)
✔ All packages installed (365 packages installed from npm registry, used 8s(network 4s), speed 181.31kB/s, json 339(788.88kB), tarball 0B)

运行结果截图如下:
运行结果截图

再执行:

npx electron-forge import

此时可能会报错,我的运行报错:

$ npx electron-forge import
✔ Checking your system
✔ Initializing Git Repository
✔ Writing modified package.json file
✖ Installing dependencies

An unhandled error has occurred inside Forge:
Failed to install modules: ["electron-squirrel-startup"]

With output: Command failed with a non-zero return code (1):
yarn add electron-squirrel-startup
yarn add v1.15.2
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
info If you think this is a bug, please open a bug report with the information provided in "/Users/sunct/work/my-electron-app/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

warning @electron-forge/cli > @electron-forge/core > nugget > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
warning @electron-forge/cli > @electron-forge/core > electron-rebuild > node-gyp > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
warning @electron-forge/cli > @electron-forge/core > electron-rebuild > lzma-native > node-pre-gyp@0.11.0: Please upgrade to @mapbox/node-pre-gyp: the non-scoped node-pre-gyp package is deprecated and only the @mapbox scoped package will recieve updates in the future
warning @electron-forge/cli > @electron-forge/core > nugget > request > har-validator@5.1.5: this library is no longer supported
warning @electron-forge/cli > @electron-forge/core > nugget > request > uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
error An unexpected error occurred: "EINVAL: invalid argument, unlink '/Users/sunct/work/my-electron-app/node_modules/electron-notarize/node_modules/fs-extra'".
warning @electron-forge/cli > @electron-forge/core > nugget > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
warning @electron-forge/cli > @electron-forge/core > electron-rebuild > node-gyp > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
warning @electron-forge/cli > @electron-forge/core > electron-rebuild > lzma-native > node-pre-gyp@0.11.0: Please upgrade to @mapbox/node-pre-gyp: the non-scoped node-pre-gyp package is deprecated and only the @mapbox scoped package will recieve updates in the future
warning @electron-forge/cli > @electron-forge/core > nugget > request > har-validator@5.1.5: this library is no longer supported
warning @electron-forge/cli > @electron-forge/core > nugget > request > uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
error An unexpected error occurred: "EINVAL: invalid argument, unlink '/Users/sunct/work/my-electron-app/node_modules/electron-notarize/node_modules/fs-extra'".

Error: Failed to install modules: ["electron-squirrel-startup"]

With output: Command failed with a non-zero return code (1):
yarn add electron-squirrel-startup
yarn add v1.15.2
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
info If you think this is a bug, please open a bug report with the information provided in "/Users/sunct/work/my-electron-app/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

warning @electron-forge/cli > @electron-forge/core > nugget > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
warning @electron-forge/cli > @electron-forge/core > electron-rebuild > node-gyp > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
warning @electron-forge/cli > @electron-forge/core > electron-rebuild > lzma-native > node-pre-gyp@0.11.0: Please upgrade to @mapbox/node-pre-gyp: the non-scoped node-pre-gyp package is deprecated and only the @mapbox scoped package will recieve updates in the future
warning @electron-forge/cli > @electron-forge/core > nugget > request > har-validator@5.1.5: this library is no longer supported
warning @electron-forge/cli > @electron-forge/core > nugget > request > uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
error An unexpected error occurred: "EINVAL: invalid argument, unlink '/Users/sunct/work/my-electron-app/node_modules/electron-notarize/node_modules/fs-extra'".
warning @electron-forge/cli > @electron-forge/core > nugget > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
warning @electron-forge/cli > @electron-forge/core > electron-rebuild > node-gyp > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
warning @electron-forge/cli > @electron-forge/core > electron-rebuild > lzma-native > node-pre-gyp@0.11.0: Please upgrade to @mapbox/node-pre-gyp: the non-scoped node-pre-gyp package is deprecated and only the @mapbox scoped package will recieve updates in the future
warning @electron-forge/cli > @electron-forge/core > nugget > request > har-validator@5.1.5: this library is no longer supported
warning @electron-forge/cli > @electron-forge/core > nugget > request > uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
error An unexpected error occurred: "EINVAL: invalid argument, unlink '/Users/sunct/work/my-electron-app/node_modules/electron-notarize/node_modules/fs-extra'".

    at _default (/Users/sunct/work/my-electron-app/node_modules/_@electron-forge_core@6.0.0-beta.57@@electron-forge/core/src/util/install-dependencies.ts:44:11)
    at /Users/sunct/work/my-electron-app/node_modules/_@electron-forge_core@6.0.0-beta.57@@electron-forge/core/src/api/import.ts:180:5

一部分截图如下:
报错截图

最主要的一句就是 Error: Failed to install modules: ["electron-squirrel-startup"]’,报错内容是缺少electron-squirrel-startup这个模块。
缺少就手动安装一下,根据提示,执行命令如下:

yarn add electron-squirrel-startup
yarn add v1.15.2

运行结果如图:
运行结果
再次执行:

npx electron-forge import 

结果如图,表示执行成功:
执行成功

(2)、使用 Forge 的 make 命令来创建可分发的应用程序

执行以下命令:

npm run make

运行结果如图:
npm run make

Electron Forge创建包所在的out文件夹:
out文件夹
到此,就可以单独运行安装程序了。

我运行my-electron-app/out/my-electron-app-darwin-x64目录下的 my-electron-app.app,效果和执行 cnpm start效果一样。
在这里插入图片描述

下一节:使用Electron构建跨平台的桌面应用程序(二)使用React【Umijs框架】+ Electron+ Antd 来实现一个简单的计算器功能




END


如有问题请在下方留言。

或关注我的公众号“孙三苗”,输入“联系方式”。获得进一步帮助。

在这里插入图片描述

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值