蓝色天空.知识 · 实践 · 创造
我的收藏
Electron 教程目录 21章
Electron / LEARN BY DOING

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管理会话、缓存、Cookiesession.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安全暴露 APIcontextBridge.exposeInMainWorld('api', {...})在 contextIsolation 开启时向页面暴露只读安全接口
desktopCapturer捕获屏幕内容desktopCapturer.getSources({ types: ['window', 'screen'] })用于截屏与录屏源枚举(Electron 17+ 应在主进程调用)
Notification通知 APInew 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-storeJSON 配置与轻量数据持久化store.set('key', value)、store.get('key')
sqlite3 / better-sqlite3嵌入式关系型本地数据库db.prepare('SELECT * FROM notes').all()
axios / node-fetchHTTP 客户端请求封装axios.post(url, data)
node-gypC/C++ 原生插件构建编译node-gyp rebuild

package.json 核心字段说明表

字段含义
name / version / description项目包名、语义化版本号与简介
mainElectron 主进程启动入口文件(必填)
scripts常用任务脚本,如 npm start 启动与 npm run dist 打包
devDependencies开发与构建依赖(electron、electron-builder 等)
build内联于 package.json 的 electron-builder 构建配置对象
appId反向域名格式的应用唯一标识,用于签名、通知与自动更新
productName安装与窗口展示使用的产品名称
directories.output打包产物输出目录(常见为 dist)
files声明需打入应用包的源码与资源通配符列表
win/mac/linuxWindows/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 核心辅助模块实时调用及三套工程配置模板校验

含完整源码 · 180 行
展开查看收起
javascript
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 关键字段。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1081.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Electron

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip

下载课程关联工程包:Electron

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1079.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

随着多平台目标格式、签名公证、extraResources 与 publish 发布源配置增多,独立的 electron-builder.yml 能保持 package.json 简洁清晰,并支持注释与环境配置拆分维护。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习