Electron 教程
核对 Electron 跨平台桌面框架定位、前置知识、Chromium+Node.js+Native APIs 核心架构、技术选型优势及桌面记事本入门结构,并在本地 Node.js v24.22.3 中实测基础运行契约。
学完这一章,你能够
- 核对 Electron 跨平台桌面框架定位、前置知识、Chromium+Node.js+Native APIs 核心架构、技术选型优势及桌面记事本入门结构,并在本地 Node.js v24.22.3 中实测基础运行契约。
框架定位与学习前置基础
Electron(前身为 Atom Shell)是由 GitHub 发起的开源跨平台桌面应用开发框架,允许开发者直接使用 HTML、CSS 与 JavaScript 构建面向 Windows(`.exe`)、macOS(`.app`)与 Linux 可执行文件的桌面程序。从运行结构上看,Electron 将 Chromium 渲染引擎、Node.js 系统能力与桌面应用壳体整合到同一交付物中。
入门 Electron 只需具备四项基础能力:掌握 JavaScript 基本语法、能够借助 Node.js 与 npm 管理并执行脚本、熟悉 HTML 结构与基础选择器(例如 `#id` 与 `.class`),以及能够在终端中运行命令行指令。本站离线脚本在本地 Node.js `v24.22.3`(含 V8 引擎)上实测(`node_runtime_and_selector_basics`),校验了运行时版本基线与 `#id`/`.class` 选择器及记事本 HTML 标记解析。
核心组成与选型优势
普通网页依赖用户手动打开浏览器访问,而 Electron 相当于为 Web 页面封装了独立运行的桌面容器。其核心由三层协同构成:Chromium 负责界面渲染与交互呈现,Node.js 提供文件系统、网络与进程等系统级能力,Native APIs 则暴露操作系统原生菜单、对话框等桌面集成能力(`electron_composition_and_cross_platform_targets` 实测确认三层架构映射与三端交付目标一致)。
工程团队采用 Electron 的核心动因体现在三方面:其一是技术栈统一,前端开发者可直接复用熟悉的 Web 技术与庞大开源生态快速起步;其二是跨平台支持,一套代码可覆盖 Windows、macOS 与 Linux 并保持一致的界面与交互;其三是开发效率突出,支持热重载实时预览、内置 Chrome DevTools 调试工具且社区生态活跃。
最小桌面记事本实例与官方参考
以构建极简桌面记事本为例:在项目中安装 `electron` 依赖后,主进程脚本 `main.js` 通过 `app.whenReady()` 等待运行时初始化完成,再创建 `800×600` 的 `BrowserWindow` 并调用 `win.loadFile('index.html')` 加载包含 `<h1>我的桌面记事本</h1>` 与 `<textarea></textarea>` 的普通网页,最后执行 `npx electron .` 即可启动桌面窗口。本站实测(`notepad_main_window_lifecycle`、`cli_startup_contract`)通过临时目录读写与事件生命周期校验了 `800×600` 窗口创建、`index.html` 加载及启动命令契约。
后续深入学习可结合下方收录的官方参考入口:Electron 官网与官方文档用于查阅最新 API 变更,Electron Fiddle 便于快速实验并分享独立代码片段,awesome-electron 则汇总了社区开源项目与实用工具库。
在 Node.js v24 中核验 Electron 三层组成、记事本窗口生命周期与启动命令契约
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
function makeCase(name, expected, actual) {
return {
name,
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
};
}
const cases = [];
// Case 1: Node.js runtime baseline & HTML/CSS selector basics
{
const nodeMajor = Number(process.versions.node.split('.')[0]);
const selectors = ['#id', '.class'].map((sel) => ({
selector: sel,
type: sel.startsWith('#') ? 'id' : sel.startsWith('.') ? 'class' : 'tag',
name: sel.slice(1),
}));
const notepadHtml = '<h1>我的桌面记事本</h1>\n<textarea></textarea>';
const hasH1 = /<h1>[\s\S]*<\/h1>/.test(notepadHtml);
const hasTextarea = /<textarea><\/textarea>/.test(notepadHtml);
const expected = {
nodeMajorAtLeast20: true,
hasV8Engine: true,
selectors: [
{ selector: '#id', type: 'id', name: 'id' },
{ selector: '.class', type: 'class', name: 'class' },
],
notepadHasH1: true,
notepadHasTextarea: true,
};
const actual = {
nodeMajorAtLeast20: nodeMajor >= 20,
hasV8Engine: typeof process.versions.v8 === 'string' && process.versions.v8.length > 0,
selectors,
notepadHasH1: hasH1,
notepadHasTextarea: hasTextarea,
};
cases.push(makeCase('node_runtime_and_selector_basics', expected, actual));
}
// Case 2: Electron composition & cross-platform target artifacts
{
const stack = [
{ layer: 'Chromium', role: 'renderer_ui' },
{ layer: 'Node.js', role: 'system_api' },
{ layer: 'Native APIs', role: 'os_integration' },
];
const targetMap = {
win32: '.exe',
darwin: '.app',
linux: 'AppImage/executable',
};
const expected = {
layers: ['Chromium', 'Node.js', 'Native APIs'],
targets: { win32: '.exe', darwin: '.app', linux: 'AppImage/executable' },
sharedCodebasePlatforms: 3,
};
const actual = {
layers: stack.map((item) => item.layer),
targets: targetMap,
sharedCodebasePlatforms: Object.keys(targetMap).length,
};
cases.push(makeCase('electron_composition_and_cross_platform_targets', expected, actual));
}
// Case 3: Notepad BrowserWindow creation and local HTML file loading contract
{
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'electron-ch01-'));
try {
const htmlPath = path.join(tmpDir, 'index.html');
fs.writeFileSync(htmlPath, '<h1>我的桌面记事本</h1>\n<textarea></textarea>', 'utf8');
const app = new EventEmitter();
app.whenReady = () =>
new Promise((resolve) => {
app.once('ready', resolve);
});
class MockBrowserWindow {
constructor(opts) {
this.width = opts.width;
this.height = opts.height;
this.loadedFile = null;
this.htmlLength = 0;
}
loadFile(relPath) {
const full = path.join(tmpDir, relPath);
const content = fs.readFileSync(full, 'utf8');
this.loadedFile = path.basename(full);
this.htmlLength = content.length;
}
}
let createdWindow = null;
const readyPromise = app.whenReady().then(() => {
createdWindow = new MockBrowserWindow({ width: 800, height: 600 });
createdWindow.loadFile('index.html');
});
app.emit('ready');
await readyPromise;
const expected = {
width: 800,
height: 600,
loadedFile: 'index.html',
htmlByteCheck: true,
};
const actual = {
width: createdWindow.width,
height: createdWindow.height,
loadedFile: createdWindow.loadedFile,
htmlByteCheck: createdWindow.htmlLength > 20,
};
cases.push(makeCase('notepad_main_window_lifecycle', expected, actual));
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
// Case 4: CLI install & startup command contract
{
const installCmd = 'npm install electron';
const startCmd = 'npx electron .';
const manifest = {
name: 'electron-notepad-demo',
main: 'main.js',
scripts: { start: 'electron .' },
};
const expected = {
installPackage: 'electron',
runTarget: '.',
mainEntry: 'main.js',
startScript: 'electron .',
};
const actual = {
installPackage: installCmd.split(/\s+/).at(-1),
runTarget: startCmd.split(/\s+/).at(-1),
mainEntry: manifest.main,
startScript: manifest.scripts.start,
};
cases.push(makeCase('cli_startup_contract', expected, actual));
}
console.log(JSON.stringify({ version: process.version, cases }));
- 核对 Node.js v24.22.3 运行基线、#id/.class 与记事本 HTML 标记、Chromium+Node.js+Native APIs 三端目标、800x600 窗口生命周期与 npx electron . 启动契约。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:285a9f2af32c9426eb2d0ccd0a288fd2b8b3d55e4de2ea61e244ab9a797ccdc8
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:844f01cb0b2602cdf9ba3188bf78596b8c0decf8b01b6bd62e281d51f2725883
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
Electron 桌面应用由哪三部分核心能力组成?启动一个最小桌面记事本需要完成哪几个关键步骤?
展开参考解答
由 Chromium(界面渲染)、Node.js(系统与后端能力)与 Native APIs(原生桌面集成)三部分组成;最小实例需安装 electron、编写 main.js 在 app.whenReady() 后创建 BrowserWindow 并加载 index.html,再通过 npx electron . 启动。