Electron开发Skill electron-dev

这个技能是关于使用 Electron 框架进行桌面应用开发的指南,专注于 IPC 通信、安全要求和跨进程通信模式。适用于基于 Node.js 和 Web 技术构建跨平台桌面应用,涵盖 IPC 处理器、预加载脚本、本地集成和文件系统操作。关键词:Electron 开发, IPC 通信, 安全指南, 桌面应用, 跨平台开发, 前端技术, 桌面软件开发

前端开发 0 次安装 0 次浏览 更新于 3/18/2026

name: electron-dev description: Gemini-Subtitle-Pro 项目的 Electron 主进程和 IPC 开发指南。适用于处理 IPC 处理器、预加载脚本、本地集成(ffmpeg、whisper、yt-dlp)、文件系统操作和桌面特定功能。涵盖安全要求、IPC 模式和跨进程通信。

Electron 开发指南

目的

为 Gemini-Subtitle-Pro 中的 Electron 主进程开发建立安全和一致的模式。

何时使用此技能

自动激活当处理:

  • 创建或修改 IPC 处理器
  • 处理预加载脚本
  • 本地集成(ffmpeg、whisper、yt-dlp)
  • 文件系统操作
  • 桌面特定功能
  • 协议处理器

快速开始

新 IPC 通道检查清单

  • [ ] 处理器: 在 electron/main.ts 中使用 ipcMain.handle() 添加
  • [ ] 桥接: 在 electron/preload.ts 中通过 contextBridge 暴露
  • [ ] 类型: 更新 src/types/electron.d.ts
  • [ ] 命名: 使用 feature:action 约定

安全要求(关键)

这些设置必须在 electron/main.ts 中维护:

const mainWindow = new BrowserWindow({
  webPreferences: {
    nodeIntegration: false, // 永远不要改为 true
    contextIsolation: true, // 永远不要改为 false
    sandbox: true, // 永远不要改为 false
    preload: path.join(__dirname, 'preload.js'),
  },
});

为什么?

  • nodeIntegration: false - 防止渲染器直接访问 Node.js API
  • contextIsolation: true - 分离预加载和渲染器上下文
  • sandbox: true - 限制预加载脚本功能

IPC 合同模式

步骤 1: 处理器在 main.ts 中

// electron/main.ts
ipcMain.handle('video:compress', async (event, options: CompressOptions) => {
  try {
    const result = await compressVideo(options);
    return { success: true, data: result };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

步骤 2: 桥接在 preload.ts 中

// electron/preload.ts
contextBridge.exposeInMainWorld('electronAPI', {
  compressVideo: (options: CompressOptions) => ipcRenderer.invoke('video:compress', options),
});

步骤 3: 类型在 electron.d.ts 中

// src/types/electron.d.ts
interface ElectronAPI {
  compressVideo: (options: CompressOptions) => Promise<CompressResult>;
}

declare global {
  interface Window {
    electronAPI: ElectronAPI;
  }
}

步骤 4: 在渲染器中使用

// src/services/video/compressor.ts
const result = await window.electronAPI.compressVideo(options);

目录结构

electron/
├── main.ts              # 主进程入口,IPC 处理器
├── preload.ts           # 上下文桥接
├── logger.ts            # 日志工具
├── i18n.ts              # 主进程国际化
├── locales/             # 主进程本地化文件
└── services/            # 本地服务集成
    ├── ffmpegService.ts
    ├── localWhisper.ts
    └── videoPreviewTranscoder.ts

命名约定

IPC 通道

使用 feature:action 格式:

// ✅ 好
'video:compress';
'audio:extract';
'subtitle:export';
'file:select';
'app:getVersion';

// ❌ 不好
'compressVideo';
'COMPRESS_VIDEO';
'video_compress';

资源文件

详细指南见资源目录: