Electron desktop development

From findscripter/everything-skills · View interactive version

Electron desktop development is an AI agent skill from the GitHub repository findscripter/everything-skills. 当用 Electron 构建/加固/打包跨平台桌面应用时使用;做安全的多进程架构(contextIsolation/sandbox + preload 白名单 IPC)、electron-builder 打包签名与 electron-updater 自动更新,产出可上线的工程骨架与配置;不适用于纯 Web 应用、Tauri、Chrome 扩展、移动端。触发词:Electron、preload、IPC、electron-builder、自动更新、代码签名

How to use this skill

Skill file

何时使用

适用场景:

不该用(负边界):

步骤

  1. 梳理项目结构,划清进程边界(main / preload / renderer / shared)。shared/ 只放类型、常量、枚举,绝不放跨进程导入的可执行代码。
  2. 强制安全默认值:contextIsolation: true、nodeIntegration: false、sandbox: true、webSecurity: true。
  3. 在 preload 中用 contextBridge 暴露 API,并对 IPC 通道做显式白名单。
  4. 用合适工具链实现、测试、构建(electron-vite + Vite HMR;Playwright 做 E2E)。
  5. 上线前逐项核对「生产安全清单」。

指令

推荐目录结构(关键):

src/
  main/      main.ts / ipc-handlers.ts / menu.ts / tray.ts / updater.ts
  preload/   preload.ts   # main ↔ renderer 桥
  renderer/  index.html / App.tsx / components / styles
  shared/    constants.ts(通道名) / types.ts(共享类型)
resources/   icon.png(1024x1024) / entitlements.mac.plist

进程模型(隔离设计):

| 进程 | 职责 | Node 访问 | DOM 访问 |

|------|------|----------|---------|

| Main | 生命周期、窗口、原生 API、IPC 枢纽 | 完整 | 无 |

| Renderer | UI 渲染与交互 | 默认无 | 有 |

| Preload | main↔renderer 安全桥 | 受限(经 contextBridge) | 页面加载前 |

| Utility | CPU 密集/后台任务 | 完整 | 无 |

IPC 三种模式:

| 模式 | 方法 | 场景 |

|------|------|------|

| 单向即发即忘 | ipcRenderer.send() → ipcMain.on() | 日志、埋点、非关键通知 |

| 请求/响应 | ipcRenderer.invoke() → ipcMain.handle() | 文件操作、对话框、数据查询 |

| 推送到渲染端 | webContents.send() → ipcRenderer.on() | 进度、下载状态、自动更新 |

生产环境永远不要用 ipcRenderer.sendSync(),它会阻塞渲染进程事件循环、冻结 UI。

代码签名(构建前设置环境变量):

# macOS(需 Apple Developer 证书)
export CSC_LINK="path/to/Developer_ID_Application.p12"
export CSC_KEY_PASSWORD="your-password"
# Windows(需 EV 或标准代码签名证书)
export WIN_CSC_LINK="path/to/code-signing.pfx"
export WIN_CSC_KEY_PASSWORD="your-password"
npx electron-builder --mac --win --publish never

原生模块装好后重建 ABI:npx @electron/rebuild

示例

带安全默认值的 BrowserWindow(强制):

const win = new BrowserWindow({
  width: 1200, height: 800,
  webPreferences: {
    contextIsolation: true,   // 永远不要改
    nodeIntegration: false,
    sandbox: true,
    preload: path.join(__dirname, '../preload/preload.js'),
    webSecurity: true,
    allowRunningInsecureContent: false,
  },
});
// CSP 头
win.webContents.session.webRequest.onHeadersReceived((details, cb) => {
  cb({ responseHeaders: { ...details.responseHeaders,
    'Content-Security-Policy': ["default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:;"] } });
});

preload 白名单桥:

import { contextBridge, ipcRenderer } from 'electron';
const ALLOWED_SEND = ['file:save', 'file:open', 'app:get-version'] as const;
const ALLOWED_RECV = ['file:saved', 'update:available', 'update:progress'] as const;

contextBridge.exposeInMainWorld('electronAPI', {
  invoke: (ch, ...a) => ALLOWED_SEND.includes(ch)
    ? ipcRenderer.invoke(ch, ...a)
    : Promise.reject(new Error(`Channel "${ch}" not allowed`)),
  on: (ch, cb) => {
    if (!ALLOWED_RECV.includes(ch)) return () => {};
    const l = (_e, ...a) => cb(...a);
    ipcRenderer.on(ch, l);
    return () => ipcRenderer.removeListener(ch, l);
  },
});

主进程 handler(务必校验输入):

ipcMain.handle('file:save', async (_e, filePath: string, content: string) => {
  if (typeof filePath !== 'string' || typeof content !== 'string')
    throw new Error('Invalid arguments');   // 渲染端数据一律视为不可信
  await writeFile(filePath, content, 'utf-8');
  return { success: true };
});

拦截导航劫持与新窗口:

win.webContents.on('will-navigate', (e, url) => {
  if (new URL(url).origin !== 'http://localhost:5173') e.preventDefault();
});
win.webContents.setWindowOpenHandler(({ url }) => {
  const u = new URL(url);
  const allow = new Set(['example.com']);
  if (u.protocol === 'https:' && allow.has(u.hostname))
    require('electron').shell.openExternal(u.toString());
  return { action: 'deny' };  // 拦截所有新建 Electron 窗口
});

electron-builder.yml(要点):

appId: com.mycompany.myapp
productName: My App
asar: true
compression: maximum
files: ["out/**/*", "renderer/**/*", "package.json"]  # 只打编译产物
mac: { hardenedRuntime: true, entitlements: resources/entitlements.mac.plist,
       target: [{ target: dmg, arch: [x64, arm64] }] }
win: { target: [{ target: nsis, arch: [x64, arm64] }] }
linux: { target: [{ target: AppImage }, { target: deb }] }
publish: { provider: github, owner: your-org, repo: your-repo }

自动更新(electron-updater):

autoUpdater.autoDownload = false;          // 让用户决定
autoUpdater.autoInstallOnAppQuit = true;
autoUpdater.on('update-available', i => win.webContents.send('update:available', { version: i.version }));
autoUpdater.on('download-progress', p => win.webContents.send('update:progress', { percent: Math.round(p.percent) }));
autoUpdater.on('update-downloaded', () => win.webContents.send('update:downloaded'));
setInterval(() => autoUpdater.checkForUpdates(), 4 * 60 * 60 * 1000);
ipcMain.handle('update:download', () => autoUpdater.downloadUpdate());
ipcMain.handle('update:install', () => autoUpdater.quitAndInstall());

Playwright 启动 Electron 做 E2E:

import { test, expect, _electron as electron } from '@playwright/test';
test('launches main window', async () => {
  const app = await electron.launch({ args: ['.'] });
  const win = await app.firstWindow();
  await win.waitForLoadState('domcontentloaded');
  expect(await win.title()).toBe('My App');
  await app.close();
});

注意事项

生产安全清单(上线前逐项核对):

常见问题速诊:

框架固有局限:

互见


采编自 sickn33/antigravity-awesome-skills(MIT)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.