Electron API 速查与配置模板
系统梳理 Electron 主进程 14 个核心模块、渲染进程 9 类常用接口、8 类 Node/生态辅助模块,以及 package.json、electron-builder.yml 与 tsconfig.json 标准模板。
学完这一章,你能够
- 系统梳理 Electron 主进程 14 个核心模块、渲染进程 9 类常用接口、8 类 Node/生态辅助模块,以及 package.json、electron-builder.yml 与 tsconfig.json 标准模板。
主进程与渲染进程 API 速查矩阵
主进程负责应用生命周期、窗口编排、系统原生交互与底层网络控制。下表汇总 `app`、`BrowserWindow`、`ipcMain`、`Menu`、`Tray`、`Dialog`、`Notification`、`Shell`、`Protocol`、`Session`、`Net`、`PowerMonitor`、`Clipboard` 与 `GlobalShortcut` 共 14 个核心模块的职责与代表方法。本站离线实测(`main_process_api_matrix`)核对了 14 个主进程模块注册清单与生命周期/IPC 入口。
渲染进程面向 UI 与 Web 能力,在开启 `contextIsolation` 时通过预加载脚本中的 `contextBridge` 与 `ipcRenderer` 同主进程通信(注:Electron 17+ 中 `desktopCapturer.getSources` 已迁移至主进程调用后经 IPC 返回渲染进程)。下表整理了 9 类常用渲染进程与 Web API,本站离线实测(`renderer_process_api_matrix`)验证了全部 9 项接口分类及 3 项预加载安全边界模块。
常用辅助模块与核心配置文件模板
除 Electron 内置模块外,主进程与构建脚本还高频依赖 Node.js 核心库(`fs`、`path`、`os`、`child_process`)及桌面生态库(`electron-store`、`sqlite3 / better-sqlite3`、`axios / node-fetch`、`node-gyp`)。本站离线实测(`node_and_ecosystem_helpers_live`)在临时目录真实执行了 `fs` 读写、`path.basename`、`os.platform`/`os.homedir` 及 `child_process.execFileSync` 子进程返回 `child-ok`,并核对 8 项辅助模块清单。
工程配置方面,`package.json` 需明确主进程入口 `main`、开发与打包命令 `scripts`(`npm start`、`npm run dist`)、`devDependencies` 以及 `build` 下的 `appId`、`productName`、`directories.output`、`files` 与 `win/mac/linux` 平台配置;若配置项较复杂,也可抽离为独立 `electron-builder.yml` 并补充 `publish` 发布源(如 GitHub Releases)。本站离线实测(`package_and_builder_yaml_templates`)解析并核对了 `package.json` 与 `electron-builder.yml` 两套模板的关键字段。
使用 TypeScript 编写 Electron 主进程与预加载代码时,`tsconfig.json` 建议将 `target` 设为 `ES2020`、`module` 设为 `commonjs`(与传统 Electron 主进程加载机制兼容),并启用 `strict`、`esModuleInterop`、`resolveJsonModule` 与 `skipLibCheck`,同时区分 `rootDir`(`./src`)与 `outDir`(`./dist`)。本站离线实测(`tsconfig_template_validation`)验证了全部 8 项核心编译选项契约。
主进程 API 速查表
| 模块 | 功能描述 | 常用方法 | 说明 |
|---|---|---|---|
| app | 控制应用生命周期 | app.on('ready')、app.quit()、app.getPath('userData') | 管理应用启动、退出、系统路径与协议注册 |
| BrowserWindow | 创建与管理窗口 | new BrowserWindow(options)、win.loadFile()、win.loadURL()、win.webContents | 应用核心 UI 容器,每个窗口托管独立渲染进程 |
| ipcMain | 主进程通信接口 | ipcMain.on(channel, callback)、ipcMain.handle(channel, handler) | 监听渲染进程单向消息或处理异步请求响应 |
| Menu | 创建应用菜单 | Menu.buildFromTemplate(menuTemplate)、Menu.setApplicationMenu(menu) | 构建顶部应用菜单、右键上下文菜单及快捷键 |
| Tray | 系统托盘管理 | new Tray(icon)、tray.setToolTip()、tray.setContextMenu(menu) | 在系统通知区显示托盘图标,常用于后台常驻 |
| Dialog | 系统原生对话框 | dialog.showOpenDialog()、dialog.showSaveDialog()、dialog.showMessageBox() | 调用文件打开/保存选择器与原生消息框 |
| Notification | 系统通知 | new Notification({ title, body }).show() | 触发操作系统原生通知并支持点击回调 |
| Shell | 调用系统外部资源 | shell.openExternal(url)、shell.showItemInFolder(path) | 使用默认浏览器打开安全链接或定位本地文件夹 |
| Protocol | 注册自定义协议 | protocol.registerFileProtocol()、protocol.handle() | 拦截自定义 URL scheme 加载资源或处理深度链接 |
| Session | 管理会话、缓存、Cookie | session.defaultSession.cookies.get()、clearCache() | 底层控制网络代理、请求拦截、缓存与 Cookie |
| Net | 原生 HTTP/HTTPS 网络请求 | net.request(options) | 基于 Chromium 网络栈的底层请求模块,自动集成系统代理 |
| PowerMonitor | 监控系统电源状态 | powerMonitor.on('suspend')、on('resume') | 监听休眠、唤醒、锁屏与电池供电切换事件 |
| Clipboard | 剪贴板操作 | clipboard.readText()、clipboard.writeText() | 跨平台读写系统剪贴板文本、HTML 与图片 |
| GlobalShortcut | 注册全局快捷键 | globalShortcut.register('CommandOrControl+X', fn) | 在应用后台失焦时仍可响应的全局热键 |
渲染进程 API 速查表
| 模块 | 功能描述 | 常用方法 | 说明 |
|---|---|---|---|
| ipcRenderer | 与主进程通信 | ipcRenderer.send()、ipcRenderer.invoke()、ipcRenderer.on() | 在 preload 脚本中收发消息与调用主进程 handler |
| webFrame | 控制当前页面内容 | webFrame.setZoomFactor()、webFrame.insertCSS() | 动态调整当前页面缩放比例与注入样式 |
| contextBridge | 安全暴露 API | contextBridge.exposeInMainWorld('api', {...}) | 在 contextIsolation 开启时向页面暴露只读安全接口 |
| desktopCapturer | 捕获屏幕内容 | desktopCapturer.getSources({ types: ['window', 'screen'] }) | 用于截屏与录屏源枚举(Electron 17+ 应在主进程调用) |
| Notification | 通知 API | new Notification('标题', { body: '内容' }) | 调用浏览器标准 Web Notification API 发送提醒 |
| Clipboard | 剪贴板操作 | navigator.clipboard.readText() | 基于浏览器安全上下文访问系统剪贴板 |
| Web Storage / IndexedDB | 本地存储 | localStorage.setItem()、indexedDB.open() | 在浏览器存储区保存轻量键值或结构化数据 |
| Fetch / Axios | 网络请求 | fetch(url)、axios.get() | 在页面层访问 HTTP 接口与加载远程资源 |
| DOM / Window | 页面控制 | document.querySelector()、window.open() | 完整复用标准浏览器 DOM 与 Web 平台 API |
常用辅助模块速查表
| 模块 | 主要功能 | 示例 |
|---|---|---|
| fs | 本地文件与目录读写 | fs.readFileSync(path)、fs.writeFile(path, data) |
| path | 跨平台路径规范拼接 | path.join(__dirname, 'index.html') |
| os | 查询操作系统与用户目录信息 | os.platform()、os.homedir() |
| child_process | 拉起外部命令或子进程 | exec('ls', callback)(建议优先使用 execFile 防注入) |
| electron-store | JSON 配置与轻量数据持久化 | store.set('key', value)、store.get('key') |
| sqlite3 / better-sqlite3 | 嵌入式关系型本地数据库 | db.prepare('SELECT * FROM notes').all() |
| axios / node-fetch | HTTP 客户端请求封装 | axios.post(url, data) |
| node-gyp | C/C++ 原生插件构建编译 | node-gyp rebuild |
package.json 核心字段说明表
| 字段 | 含义 |
|---|---|
| name / version / description | 项目包名、语义化版本号与简介 |
| main | Electron 主进程启动入口文件(必填) |
| scripts | 常用任务脚本,如 npm start 启动与 npm run dist 打包 |
| devDependencies | 开发与构建依赖(electron、electron-builder 等) |
| build | 内联于 package.json 的 electron-builder 构建配置对象 |
| appId | 反向域名格式的应用唯一标识,用于签名、通知与自动更新 |
| productName | 安装与窗口展示使用的产品名称 |
| directories.output | 打包产物输出目录(常见为 dist) |
| files | 声明需打入应用包的源码与资源通配符列表 |
| win/mac/linux | Windows/macOS/Linux 各自的目标格式与图标配置 |
electron-builder.yml 核心配置项说明表
| 配置项 | 说明 |
|---|---|
| appId / productName | 应用唯一标识符与安装包展示名称 |
| directories.output | 构建产物输出目录路径 |
| files | 参与打包的文件与目录匹配规则(支持 glob 通配符) |
| win / mac / linux | 三平台各自的构建目标格式与图标路径配置 |
| publish | 自动更新发布源配置(如 GitHub Releases 的 owner/repo) |
TypeScript tsconfig.json 核心选项说明表
| 选项 | 含义 |
|---|---|
| target | 编译输出的 ECMAScript 目标版本(如 ES2020) |
| module | 模块规范,Electron 主进程传统常用 commonjs |
| outDir / rootDir | 编译产物目录(./dist)与源码根目录(./src) |
| strict | 开启 TypeScript 严格类型检查集合 |
| esModuleInterop | 启用 CommonJS 与 ES 模块默认导入互操作 |
| resolveJsonModule | 允许在 TypeScript 源码中直接导入 JSON 文件 |
| skipLibCheck | 跳过第三方 .d.ts 声明文件检查以提升编译速度 |
离线实测主/渲染进程 API 矩阵、Node.js 核心辅助模块实时调用及三套工程配置模板校验
import { execFileSync } from 'node:child_process';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function caseMainProcessApiMatrix() {
const mainModules = [
'app', 'BrowserWindow', 'ipcMain', 'Menu', 'Tray', 'Dialog', 'Notification',
'Shell', 'Protocol', 'Session', 'Net', 'PowerMonitor', 'Clipboard', 'GlobalShortcut',
];
const lifecycleApis = ["app.on('ready')", 'app.quit()', "app.getPath('userData')"];
const ipcApis = ['ipcMain.on', 'ipcMain.handle'];
const actual = {
moduleCount: mainModules.length,
firstModule: mainModules[0],
lastModule: mainModules[mainModules.length - 1],
lifecycleCount: lifecycleApis.length,
ipcApis,
};
const expected = {
moduleCount: 14,
firstModule: 'app',
lastModule: 'GlobalShortcut',
lifecycleCount: 3,
ipcApis: ['ipcMain.on', 'ipcMain.handle'],
};
return { name: 'main_process_api_matrix', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
function caseRendererProcessApiMatrix() {
const rendererModules = [
'ipcRenderer', 'webFrame', 'contextBridge', 'desktopCapturer', 'Notification',
'Clipboard', 'Web Storage / IndexedDB', 'Fetch / Axios', 'DOM / Window',
];
const preloadSafeApis = ['ipcRenderer', 'contextBridge', 'webFrame'];
const actual = {
moduleCount: rendererModules.length,
hasContextBridge: rendererModules.includes('contextBridge'),
preloadSafeCount: preloadSafeApis.length,
lastModule: rendererModules[rendererModules.length - 1],
};
const expected = {
moduleCount: 9,
hasContextBridge: true,
preloadSafeCount: 3,
lastModule: 'DOM / Window',
};
return { name: 'renderer_process_api_matrix', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
async function caseNodeAndEcosystemHelpersLive() {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'electron-apis-'));
try {
const filePath = path.join(tmpDir, 'index.html');
await fs.writeFile(filePath, '<h1>Electron</h1>', 'utf8');
const content = await fs.readFile(filePath, 'utf8');
const childOut = execFileSync(process.execPath, ['-e', 'process.stdout.write("child-ok")'], { encoding: 'utf8' });
const ecosystemHelpers = ['fs', 'path', 'os', 'child_process', 'electron-store', 'sqlite3 / better-sqlite3', 'axios / node-fetch', 'node-gyp'];
const actual = {
fsRoundTrip: content === '<h1>Electron</h1>',
pathBasename: path.basename(filePath),
osPlatformNonEmpty: os.platform().length > 0,
osHomedirNonEmpty: os.homedir().length > 0,
childOut,
helperCount: ecosystemHelpers.length,
};
const expected = {
fsRoundTrip: true,
pathBasename: 'index.html',
osPlatformNonEmpty: true,
osHomedirNonEmpty: true,
childOut: 'child-ok',
helperCount: 8,
};
return { name: 'node_and_ecosystem_helpers_live', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
}
function casePackageAndBuilderYamlTemplates() {
const pkg = {
name: 'my-electron-app',
version: '1.0.0',
description: '示例 Electron 应用',
main: 'main.js',
scripts: { start: 'electron .', pack: 'electron-builder --dir', dist: 'electron-builder' },
devDependencies: { electron: '^33.0.0', 'electron-builder': '^24.6.0' },
build: {
appId: 'com.example.myelectronapp',
productName: 'MyElectronApp',
directories: { output: 'dist' },
files: ['main.js', 'preload.js', 'renderer/**/*'],
win: { target: 'nsis', icon: 'assets/icon.ico' },
mac: { category: 'public.app-category.productivity', icon: 'assets/icon.icns' },
linux: { target: 'AppImage', icon: 'assets/' },
},
};
const ymlSnippet = [
'appId: com.example.myelectronapp',
'productName: MyElectronApp',
'directories:',
' output: dist',
'publish:',
' provider: github',
' repo: my-electron-app',
' owner: username',
].join('\n');
const actual = {
pkgMain: pkg.main,
scriptKeys: Object.keys(pkg.scripts),
buildFilesCount: pkg.build.files.length,
ymlAppId: ymlSnippet.match(/^appId:\s*(.+)$/m)?.[1].trim(),
ymlPublishProvider: ymlSnippet.match(/provider:\s*(.+)$/m)?.[1].trim(),
};
const expected = {
pkgMain: 'main.js',
scriptKeys: ['start', 'pack', 'dist'],
buildFilesCount: 3,
ymlAppId: 'com.example.myelectronapp',
ymlPublishProvider: 'github',
};
return { name: 'package_and_builder_yaml_templates', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
function caseTsconfigTemplateValidation() {
const tsconfig = {
compilerOptions: {
target: 'ES2020',
module: 'commonjs',
strict: true,
outDir: './dist',
rootDir: './src',
esModuleInterop: true,
moduleResolution: 'node',
resolveJsonModule: true,
skipLibCheck: true,
},
include: ['src/**/*'],
exclude: ['node_modules'],
};
const co = tsconfig.compilerOptions;
const actual = {
target: co.target,
module: co.module,
strict: co.strict,
outDir: co.outDir,
rootDir: co.rootDir,
esModuleInterop: co.esModuleInterop,
resolveJsonModule: co.resolveJsonModule,
skipLibCheck: co.skipLibCheck,
};
const expected = {
target: 'ES2020',
module: 'commonjs',
strict: true,
outDir: './dist',
rootDir: './src',
esModuleInterop: true,
resolveJsonModule: true,
skipLibCheck: true,
};
return { name: 'tsconfig_template_validation', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
const cases = [
caseMainProcessApiMatrix(),
caseRendererProcessApiMatrix(),
await caseNodeAndEcosystemHelpersLive(),
casePackageAndBuilderYamlTemplates(),
caseTsconfigTemplateValidation(),
];
console.log(JSON.stringify({ version: process.version, cases }));
- 核对 14 个主进程模块、9 类渲染接口、fs/path/os/child_process 真实执行(child-ok)及 package.json / electron-builder.yml / tsconfig.json 关键字段。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:32d419da312566466076d9b01e52701febef42b7c94ab7a47c1fbc1220264ebb
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:5cb1ee38bec758c79055ece53d4dfcd016126e6e6ff291bdc10c1d81eeb3a666
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Electron 模板配置中,为什么常把 electron-builder 配置从 package.json 抽离到独立的 electron-builder.yml?
展开参考解答
随着多平台目标格式、签名公证、extraResources 与 publish 发布源配置增多,独立的 electron-builder.yml 能保持 package.json 简洁清晰,并支持注释与环境配置拆分维护。