构建您的第一个应用程序
按照教程进行作
这是 Electron 教程的第 2 部分。
先决条件
构建您的第一个应用程序
使用预加载脚本
添加功能
打包您的应用程序
发布和更新
学习目标
在本教程的这一部分中,您将学习如何设置 Electron 项目 并编写一个最小的入门应用程序。在本节结束时, 您应该能够在开发模式下运行一个有效的 Electron 应用程序,来自 您的终端。
设置项目
避免 WSL
如果您使用的是 Windows 计算机,请不要使用适用于 Linux 的 Windows 子系统 (WSL) 在遵循本教程时,因为您在尝试执行 应用。
初始化 npm 项目
电子应用程序使用 npm 搭建脚手架,文件为 package.json 作为切入点。首先创建一个文件夹并初始化一个 npm 包 在其中有 .npm init
npm
纱
mkdir my-electron-app && cd my-electron-app
npm init
此命令将提示您在package.json中配置一些字段。 出于本教程的目的,需要遵循一些规则:
入口点应该是(你很快就会创建该文件)。main.js
author、license 和 description 可以是任何值,但以后打包时将是必需的。
使用常规文件夹安装依赖项node_modules
Electron 的打包工具链要求文件夹物理位于磁盘上,在 npm 安装节点依赖项的方式。默认情况下,Yarn Berry 和 pnpm 都使用替代安装策略。node_modules
因此,如果您使用 那些包管理器。
然后,将 Electron 安装到应用程序的 devDependencies 中,这是外部 生产中不需要仅开发包依赖项。
为什么 Electron 是开发依赖项?
这似乎有悖常理,因为你的生产代码正在运行 Electron API。在引擎盖下, Electron 的 JavaScript API 绑定到包含其实现的二进制文件。包装步骤 Electron 处理此二进制文件的捆绑,无需将其指定为生产 屬地。
npm
纱
npm install electron --save-dev
警告
为了正确安装 Electron,您需要确保其生命周期 脚本能够运行。这意味着避免在 npm 上使用标志,并允许列入在其他包管理器上运行构建脚本的权限。postinstall--ignore-scriptselectron
这可能会在 Electron 的未来版本中改变。有关更多详细信息,请参阅 electron/rfcs#22。
初始化包后,您的package.json文件应该如下所示 并安装 Electron。您现在还应该有一个文件夹,其中包含 Electron 可执行文件,以及指定 要安装的确切依赖项版本。node_modulespackage-lock.json
package.json
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "Hello World!",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Jane Doe",
"license": "MIT",
"devDependencies": {
"electron": "23.1.3"
}
}
高级 Electron 安装步骤
如果直接安装 Electron 失败,请参阅我们的高级安装文档,了解有关下载镜像、代理和故障排除步骤的说明。
添加 .gitignore
.gitignore 文件指定要避免跟踪的文件和目录与 Git。您应该将 GitHub 的 Node.js gitignore 模板的副本放入项目的根文件夹中,以避免提交项目的文件夹。node_modules
运行 Electron 应用程序
进一步阅读
阅读 Electron 的流程模型文档以更好地了解 Electron 的多个流程如何协同工作。
您在 package.json 中定义的主脚本是任何Electron 应用程序的入口点。该脚本控制主进程,该进程在Node.js环境中运行,负责控制应用程序的生命周期、显示本机接口、执行特权作以及管理渲染器进程(稍后会详细介绍)。
在创建您的第一个 Electron 应用程序之前,您将首先使用一个简单的脚本来确保您的main 进程入口点配置正确。在根文件夹中创建一个文件使用一行代码:main.js
main.js
console.log('Hello from Electron 👋')
因为 Electron 的主进程是一个Node.js运行时,所以你可以执行任意的Node.js代码(你甚至可以把它用作 REPL)。要执行这个脚本,add 到你package.json的 scripts 字段中的命令。这个命令会告诉 Electron 可执行文件在当前目录中查找主script 并在开发模式下运行它。electronelectron .start
package.json
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "Hello World!",
"main": "main.js",
"scripts": {
"start": "electron .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Jane Doe",
"license": "MIT",
"devDependencies": {
"electron": "23.1.3"
}
}
npm
Yarn
npm run start
Your terminal should print out . Congratulations, you have executed your first line of code in Electron! Next, you will learn how to create user interfaces with HTML and load that into a native window.Hello from Electron 👋
Loading a web page into a BrowserWindow
In Electron, each window displays a web page that can be loaded either from a local HTML file or a remote web address. For this example, you will be loading in a local file. Start by creating a barebones web page in an file in the root folder of your project: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 from Electron renderer!</title>
</head>
<body>
<h1>Hello from Electron renderer!</h1>
<p>👋</p>
</body>
</html>
Now that you have a web page, you can load it into an Electron BrowserWindow. Replace the contents of your file with the following code. We will explain each highlighted block separately.main.js
main.js
const { app, BrowserWindow } = require('electron')
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
})
Importing modules
main.js (Line 1)
const { app, BrowserWindow } = require('electron')
In the first line, we are importing two Electron modules with CommonJS module syntax:
app, which controls your application's event lifecycle.
BrowserWindow, which creates and manages app windows.
Module capitalization conventions
Typed import aliases
ES Modules in Electron
ECMAScript modules (i.e. using to load a module) are supported in Electron as of Electron 28. You can find more information about the state of ESM in Electron and how to use them in our app in our ESM guide.import
Writing a reusable function to instantiate windows
The function loads your web page into a new BrowserWindow instance:createWindow()
main.js (Lines 3-10)
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
Calling your function when the app is ready
main.js (Lines 12-14)
app.whenReady().then(() => {
createWindow()
})
Many of Electron's core modules are Node.js event emitters that adhere to Node's asynchronous event-driven architecture. The app module is one of these emitters.
In Electron, BrowserWindows can only be created after the app module's ready event is fired. You can wait for this event by using the app.whenReady() API and calling once its promise is fulfilled.createWindow()
info
You typically listen to Node.js events by using an emitter's function..on
+ app.on('ready', () => {
- app.whenReady().then(() => {
createWindow()
})
However, Electron exposes as a helper specifically for the event to avoid subtle pitfalls with directly listening to that event in particular. See electron/electron#21972 for details.app.whenReady()ready
At this point, running your Electron application's command should successfully open a window that displays your web page!start
Each web page your app displays in a window will run in a separate process called a renderer process (or simply renderer for short). Renderer processes have access to the same JavaScript APIs and tooling you use for typical front-end web development, such as using webpack to bundle and minify your code or React to build your user interfaces.
Managing your app's window lifecycle
Application windows behave differently on each operating system. Rather than enforce these conventions by default, Electron gives you the choice to implement them in your app code if you wish to follow them. You can implement basic window conventions by listening for events emitted by the app and BrowserWindow modules.
Process-specific control flow
Checking against Node's process.platform variable can help you to run code conditionally on certain platforms. Note that there are only three possible platforms that Electron can run in: (Windows), (Linux), and (macOS).win32linuxdarwin
Quit the app when all windows are closed (Windows & Linux)
On Windows and Linux, closing all windows will generally quit an application entirely. To implement this pattern in your Electron app, listen for the app module's window-all-closed event, and call app.quit() to exit your app if the user is not on macOS.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
Open a window if none are open (macOS)
In contrast, macOS apps generally continue running even without any windows open. Activating the app when no windows are available should open a new one.
To implement this feature, listen for the app module's activate event, and call your existing method if no BrowserWindows are open.createWindow()
Because windows cannot be created before the event, you should only listen for events after your app is initialized. Do this by only listening for activate events inside your existing callback.readyactivatewhenReady()
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
Final starter code
docs/fiddles/tutorial-first-app (39.0.0)
main.js
index.html
const { app, BrowserWindow } = require('electron/main')
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
Optional: Debugging from VS Code
If you want to debug your application using VS Code, you need to attach VS Code to both the main and renderer processes. Here is a sample configuration for you to run. Create a launch.json configuration in a new folder in your project:.vscode
.vscode/launch.json
{
"version": "0.2.0",
"compounds": [
{
"name": "Main + renderer",
"configurations": ["Main", "Renderer"],
"stopAll": true
}
],
"configurations": [
{
"name": "Renderer",
"port": 9222,
"request": "attach",
"type": "chrome",
"webRoot": "${workspaceFolder}"
},
{
"name": "Main",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args": [".", "--remote-debugging-port=9222"],
"outputCapture": "std",
"console": "integratedTerminal"
}
]
}
The "Main + renderer" option will appear when you select "Run and Debug" from the sidebar, allowing you to set breakpoints and inspect all the variables among other things in both the main and renderer processes.
What we have done in the file is to create 3 configurations:launch.json
Main is used to start the main process and also expose port 9222 for remote debugging (). This is the port that we will use to attach the debugger for the . Because the main process is a Node.js process, the type is set to .--remote-debugging-port=9222Renderernode
Renderer is used to debug the renderer process. Because the main process is the one that creates the process, we have to "attach" to it () instead of creating a new one. The renderer process is a web one, so the debugger we have to use is ."request": "attach"chrome
Main + renderer is a compound task that executes the previous ones simultaneously.
caution
Because we are attaching to a process in , it is possible that the first lines of your code will be skipped as the debugger will not have had enough time to connect before they are being executed. You can work around this by refreshing the page or setting a timeout before executing the code in development mode.Renderer
Further reading
If you want to dig deeper in the debugging area, the following guides provide more information:
Application Debugging
DevTools Extensions
总结
电子应用程序是使用 npm 包设置的。应该安装 Electron 可执行文件 ,可以使用 package.json文件。devDependencies
可执行文件运行在package.json属性中找到的 JavaScript 入口点。 该文件控制 Electron 的主进程,该进程运行 Node.js 的实例,并且是 负责应用的生命周期,显示本机接口,执行特权作, 以及管理渲染器进程。main
渲染器进程(或简称渲染器)负责显示图形内容。您可以 通过将网页指向网址或本地 HTML 文件,将网页加载到渲染器中。 渲染器的行为与常规网页非常相似,并且可以访问相同的 Web API。
在本教程的下一节中,我们将学习如何使用 特权 API 以及如何在进程之间进行通信。
总结并为我写出完整的步骤
最新发布