Skip to content

附录:Electron 核心知识点汇总

1. 核心模块速记(按使用频率排序,附常用方法)

app 模块

用途:控制应用生命周期

常用方法

  • app.whenReady():应用准备就绪时触发
  • app.quit():退出应用
  • app.on('window-all-closed', callback):所有窗口关闭时触发
  • app.on('activate', callback):应用激活时触发
  • app.getPath(name):获取系统路径
  • app.setAppUserModelId(id):设置应用用户模型ID(Windows)

BrowserWindow 模块

用途:创建和控制浏览器窗口

常用方法

  • new BrowserWindow(options):创建新窗口
  • win.loadFile(path):加载本地文件
  • win.loadURL(url):加载远程URL
  • win.show():显示窗口
  • win.hide():隐藏窗口
  • win.close():关闭窗口
  • win.on('closed', callback):窗口关闭时触发
  • win.webContents:获取窗口的 webContents 对象

ipcMain 模块

用途:主进程中处理渲染进程的通信

常用方法

  • ipcMain.on(channel, callback):监听渲染进程消息
  • ipcMain.handle(channel, callback):处理渲染进程的异步请求
  • ipcMain.once(channel, callback):只监听一次消息

ipcRenderer 模块

用途:渲染进程中与主进程通信

常用方法

  • ipcRenderer.send(channel, ...args):向主进程发送消息
  • ipcRenderer.invoke(channel, ...args):向主进程发送异步请求
  • ipcRenderer.on(channel, callback):监听主进程消息

webContents 模块

用途:控制网页内容

常用方法

  • webContents.loadURL(url):加载URL
  • webContents.executeJavaScript(code):执行JavaScript代码
  • webContents.on('did-finish-load', callback):页面加载完成时触发
  • webContents.on('did-fail-load', callback):页面加载失败时触发
  • webContents.openDevTools():打开开发者工具

dialog 模块

用途:显示系统对话框

常用方法

  • dialog.showOpenDialog(options):显示文件选择对话框
  • dialog.showSaveDialog(options):显示文件保存对话框
  • dialog.showMessageBox(options):显示消息框

用途:创建应用菜单和上下文菜单

常用方法

  • Menu.buildFromTemplate(template):从模板创建菜单
  • Menu.setApplicationMenu(menu):设置应用菜单
  • Menu.getApplicationMenu():获取应用菜单

Tray 模块

用途:创建系统托盘图标

常用方法

  • new Tray(image):创建托盘图标
  • tray.setToolTip(tooltip):设置托盘图标提示
  • tray.setContextMenu(menu):设置托盘上下文菜单
  • tray.on('click', callback):托盘图标点击事件

Notification 模块

用途:显示系统通知

常用方法

  • new Notification(options):创建通知
  • notification.show():显示通知
  • notification.on('click', callback):通知点击事件

2. 主进程与渲染进程区别对照表

特性主进程渲染进程
运行环境Node.js 环境Chromium 浏览器环境
API 访问完整的 Electron API有限的 Electron API(通过 contextBridge 暴露)
窗口控制可以创建和管理 BrowserWindow不能直接创建窗口
文件系统可以直接访问需要通过 IPC 与主进程通信访问
系统级 API可以直接访问需要通过 IPC 与主进程通信访问
启动方式应用启动时自动启动当创建 BrowserWindow 时启动
数量只有一个可以有多个(每个窗口一个)
崩溃影响整个应用崩溃只有当前窗口崩溃,不影响其他窗口
调试方式VS Code 调试或日志Chrome DevTools

3. IPC通信方法汇总(发送、监听、响应)

主进程 → 渲染进程

发送消息

javascript
// 主进程
win.webContents.send('message', data);

// 渲染进程
ipcRenderer.on('message', (event, data) => {
  console.log(data);
});

渲染进程 → 主进程

发送消息(单向)

javascript
// 渲染进程
ipcRenderer.send('message', data);

// 主进程
ipcMain.on('message', (event, data) => {
  console.log(data);
});

发送请求(双向,异步)

javascript
// 渲染进程
ipcRenderer.invoke('get-data', params).then(result => {
  console.log(result);
});

// 主进程
ipcMain.handle('get-data', async (event, params) => {
  // 处理请求
  return result;
});

同步请求

javascript
// 渲染进程
const result = ipcRenderer.sendSync('sync-message', data);
console.log(result);

// 主进程
ipcMain.on('sync-message', (event, data) => {
  // 处理请求
  event.returnValue = result;
});

4. 打包配置模板(多平台打包,复制即用)

package.json 配置

json
{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": "我的 Electron 应用",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "build": "electron-builder",
    "build:win": "electron-builder --win",
    "build:mac": "electron-builder --mac",
    "build:linux": "electron-builder --linux"
  },
  "build": {
    "appId": "com.example.myapp",
    "productName": "我的应用",
    "copyright": "Copyright © 2023 ${author}",
    "directories": {
      "output": "dist"
    },
    "files": [
      "main.js",
      "index.html",
      "package.json",
      "src/**/*"
    ],
    "win": {
      "target": [
        {
          "target": "nsis",
          "arch": ["x64", "ia32"]
        }
      ],
      "icon": "build/icon.ico"
    },
    "mac": {
      "target": [
        "dmg",
        "zip"
      ],
      "icon": "build/icon.icns"
    },
    "linux": {
      "target": [
        "deb",
        "rpm",
        "AppImage"
      ],
      "icon": "build/icon.png"
    },
    "nsis": {
      "oneClick": false,
      "allowElevation": true,
      "allowToChangeInstallationDirectory": true,
      "installerIcon": "build/icon.ico",
      "uninstallerIcon": "build/icon.ico",
      "installerHeaderIcon": "build/icon.ico",
      "createDesktopShortcut": true,
      "createStartMenuShortcut": true
    }
  },
  "devDependencies": {
    "electron": "^20.0.0",
    "electron-builder": "^23.0.0"
  }
}

5. 常用代码模板(窗口创建、IPC通信、本地存储等)

窗口创建

javascript
const { app, BrowserWindow } = require('electron');
const path = require('path');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      enableRemoteModule: false
    }
  });

  mainWindow.loadFile('index.html');

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});

Preload.js 模板

javascript
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  // 从渲染进程发送消息到主进程
  sendMessage: (message) => ipcRenderer.send('message', message),
  // 从渲染进程向主进程发送请求并获取响应
  getData: (params) => ipcRenderer.invoke('get-data', params),
  // 接收主进程发送的消息
  onUpdate: (callback) => ipcRenderer.on('update', (event, ...args) => callback(...args))
});

本地存储(使用 electron-store)

javascript
const Store = require('electron-store');

const store = new Store({
  defaults: {
    settings: {
      theme: 'light',
      fontSize: 14,
      autoSave: true
    },
    user: {
      name: '',
      email: ''
    }
  }
});

// 保存数据
store.set('settings.theme', 'dark');

// 读取数据
const theme = store.get('settings.theme');

// 删除数据
store.delete('user.email');

// 检查键是否存在
const hasName = store.has('user.name');

系统通知

javascript
const { Notification } = require('electron');

function showNotification(title, body) {
  const notification = new Notification({
    title: title,
    body: body,
    icon: path.join(__dirname, 'icon.png')
  });

  notification.show();

  notification.on('click', () => {
    // 处理通知点击事件
    mainWindow.show();
  });
}

// 使用
showNotification('通知标题', '通知内容');

6. 新手易错点对照表(快速排查问题)

错误现象可能原因解决方案
应用启动失败主进程文件路径错误检查 package.json 中的 main 字段是否正确
应用启动失败依赖缺失运行 npm install 安装依赖
IPC 通信失败模块引入错误检查是否正确引入 ipcMain 或 ipcRenderer
IPC 通信失败监听时机不对确保在窗口创建前注册 IPC 监听器
原生 API 调用失败权限不足检查应用权限设置
原生 API 调用失败模块未引入确保正确引入相关模块
打包后应用无法运行路径错误使用 __dirnameapp.getAppPath() 获取正确路径
打包后应用无法运行依赖打包遗漏检查 package.json 中的 files 配置
跨域问题渲染进程请求跨域在主进程中设置 webSecurity: false(开发环境)或使用代理
白屏问题页面加载失败检查 HTML 文件路径是否正确
白屏问题JavaScript 错误打开开发者工具查看错误信息

7. 常用第三方插件推荐(按场景分类)

数据存储

插件名称用途特点安装命令
electron-store本地数据存储简单易用,支持 JSON 格式npm install electron-store
nedb嵌入式数据库轻量级,无需额外服务npm install nedb
sqlite3SQLite 数据库功能强大,支持 SQLnpm install sqlite3

日志管理

插件名称用途特点安装命令
electron-log日志管理支持多级别日志、文件轮转npm install electron-log
winston日志管理功能丰富,支持多种传输方式npm install winston

应用更新

插件名称用途特点安装命令
electron-updater应用自动更新支持多种更新源npm install electron-updater
electron-auto-updater应用自动更新官方推荐npm install electron-auto-updater

UI 增强

插件名称用途特点安装命令
electron-context-menu自定义右键菜单简单易用npm install electron-context-menu
electron-tabs标签页管理支持多标签页npm install electron-tabs
electron-titlebar-windowsWindows 风格标题栏与系统风格一致npm install electron-titlebar-windows

开发工具

插件名称用途特点安装命令
electron-reload开发时热重载文件变化时自动重启npm install electron-reload --save-dev
electron-debug开发调试工具提供调试快捷键npm install electron-debug --save-dev
devtron开发工具扩展提供额外的调试功能npm install devtron --save-dev

功能扩展

插件名称用途特点安装命令
electron-dl文件下载管理支持进度条、断点续传npm install electron-dl
electron-notifications系统通知管理支持自定义图标、点击回调npm install electron-notifications
electron-prompt提示对话框简单易用,支持自定义输入npm install electron-prompt

© 2026 编程马·菜鸟教程 版权所有