moai-framework-electron by modu-ai/moai-adk
npx skills add https://github.com/modu-ai/moai-adk --skill moai-framework-electronElectron 33+ 桌面应用开发专家支持使用 Web 技术构建跨平台桌面应用程序。
自动触发:通过 electron.vite.config.ts 或 electron-builder.yml 文件检测到 Electron 项目、桌面应用开发请求、IPC 通信模式实现
Electron 33 平台:
进程架构:
IPC 通信:
自动更新支持:
打包选项:
安全功能:
创建新的 Electron 应用程序需要使用 vite-typescript 模板运行 create-electron-app 命令。将 electron-builder 安装为开发依赖项以进行打包。添加 electron-updater 作为运行时依赖项以实现自动更新功能。
有关详细命令和配置,请参阅 reference.md 快速命令部分。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
推荐目录布局:
源代码目录应包含四个主要子目录:
主目录:包含主进程入口点、按领域组织的 IPC 处理程序定义、业务逻辑服务和窗口管理模块
预加载目录:包含预加载脚本入口点和桥接主进程与渲染器的暴露 API 定义
渲染器目录:包含使用 React、Vue 或 Svelte 构建的 Web 应用程序,包括 HTML 入口点和 Vite 配置
共享目录:包含主进程和渲染器进程之间共享的 TypeScript 类型和常量
项目根目录应包含用于构建配置的 electron.vite.config.ts、用于打包选项的 electron-builder.yml 以及用于应用程序图标和资源的 resources 目录。
应用程序生命周期管理:
主进程初始化遵循特定顺序。首先,使用 app.enableSandbox() 全局启用沙盒,以确保所有渲染器进程在隔离环境中运行。然后请求单实例锁,以防止同时运行多个应用程序实例。
窗口创建应在 app ready 事件触发后进行。使用以安全为中心的 webPreferences 配置 BrowserWindow,包括启用 contextIsolation、禁用 nodeIntegration、启用沙盒和启用 webSecurity。设置预加载脚本路径,以向渲染器暴露安全的 API。
处理特定于平台的行为:在 macOS 上,如果不存在窗口,则在点击 Dock 图标时重新创建窗口。在其他平台上,当所有窗口关闭时退出应用程序。
有关实现示例,请参阅 examples.md 主进程入口点部分。
IPC 类型定义模式:
定义一个接口,将通道名称映射到其负载类型。按领域(如文件操作、窗口操作和存储操作)对通道进行分组。这支持对主进程处理程序和渲染器调用的类型检查。
主进程处理程序注册:
在专用模块中注册 IPC 处理程序,该模块从共享类型导入。每个处理程序在处理前应使用模式验证库(如 Zod)验证输入。使用 ipcMain.handle 处理请求-响应模式并返回结构化结果。
预加载脚本实现:
创建一个 API 对象,包装每个通道的 ipcRenderer.invoke 调用。使用 contextBridge.exposeInMainWorld 使此 API 在渲染器中作为 window.electronAPI 可用。包括事件监听器的清理函数以防止内存泄漏。
有关完整的 IPC 实现模式,请参阅 examples.md 类型安全的 IPC 实现部分。
强制安全设置:
每个 BrowserWindow 都必须配置 webPreferences,包含四个关键设置。必须始终启用 contextIsolation,以防止渲染器代码访问 Electron 内部。在渲染器进程中必须始终禁用 nodeIntegration。必须始终启用沙盒以实现进程级隔离。绝不能禁用 webSecurity 以保持同源策略强制执行。
内容安全策略:
使用 webRequest.onHeadersReceived 配置会话级 CSP 头。将 default-src 限制为 self,script-src 限制为 self 且不包含 unsafe-inline,connect-src 限制为允许的 API 域。这可以防止 XSS 攻击和未经授权的资源加载。
输入验证:
每个 IPC 处理程序在处理前必须验证输入。通过拒绝包含父目录引用的路径来防止路径遍历攻击。根据保留字符验证文件名。在实现文件访问时,对允许的目录使用允许列表。
有关安全实现细节,请参阅 reference.md 安全最佳实践部分。
更新服务架构:
创建一个管理 electron-updater 生命周期的 UpdateService 类。使用主窗口引用进行初始化以启用 UI 通知。将 autoDownload 配置为 false,以让用户控制带宽使用。
事件处理:
通过通知渲染器并提示用户确认下载来处理 update-available 事件。跟踪 download-progress 事件以显示进度指示器。通过提示重启来处理 update-downloaded 事件。
用户通知模式:
使用系统对话框在更新可用和下载完成时提示用户。向渲染器发送事件以显示应用内通知。支持立即和延迟安装。
有关完整的更新服务实现,请参阅 examples.md 自动更新集成部分。
Electron Builder 配置:
使用反向域名表示法配置 appId 以进行平台注册。指定 productName 以在系统 UI 中显示。为 macOS、Windows 和 Linux 设置特定于平台的目标。
macOS 配置:
设置 App Store 分类的 category。启用 hardenedRuntime 并配置 entitlements 以进行公证。配置针对 x64 和 arm64 架构的通用构建。
Windows 配置:
指定可执行文件和安装程序的图标路径。配置 NSIS 安装程序选项,包括安装目录选择。使用适当的哈希算法设置代码签名。
Linux 配置:
配置桌面环境集成的 category。设置多个目标,包括用于通用分发的 AppImage 和用于包管理器安装的 deb/rpm。
有关完整的配置示例,请参阅 reference.md 配置部分。
有关高级主题的完整文档,请参阅 reference.md 和 examples.md:
窗口状态持久化:
多窗口管理:
系统托盘和原生菜单:
实用程序进程:
原生模块集成:
协议处理程序和深度链接:
性能优化:
常见问题及解决方案:
启动时白屏:
验证预加载脚本路径是否相对于构建输出目录正确配置。检查 loadFile 或 loadURL 路径是否指向现有文件。启用 devTools 以检查控制台错误。审查可能阻止脚本执行的 CSP 设置。
IPC 不工作:
确认通道名称在主处理程序和渲染器调用之间完全匹配。确保处理程序在窗口加载内容之前注册。验证 contextBridge 的使用是否遵循正确的 exposeInMainWorld 模式。
原生模块失败:
在 npm install 后运行 electron-rebuild 以重新编译原生模块。匹配 Electron 中嵌入的 Node.js 版本。添加 postinstall 脚本以自动重建。
自动更新不工作:
验证应用程序是否已进行代码签名,因为更新需要签名。检查 electron-builder.yml 中的发布配置。启用 electron-updater 日志记录以诊断连接问题。审查可能阻止更新检查的防火墙设置。
调试命令:
使用 npx electron-rebuild 重建原生模块。使用 npx electron --version 检查 Electron 版本。使用 DEBUG=electron-updater 环境变量启用详细更新日志记录。
有关完整的代码示例和配置模板,请参阅:
有关最新文档,请使用 Context7 查询:
版本:2.0.0 最后更新:2026-01-10 变更:根据 CLAUDE.md 文档标准重构 - 删除了所有代码示例,转换为叙述性文本格式
每周安装次数
126
代码仓库
GitHub 星标数
867
首次出现
2026年1月21日
安全审计
已安装于
claude-code96
opencode89
codex89
gemini-cli87
cursor87
antigravity82
Electron 33+ Desktop App Development Specialist enables building cross-platform desktop applications with web technologies.
Auto-Triggers: Electron projects detected via electron.vite.config.ts or electron-builder.yml files, desktop app development requests, IPC communication pattern implementation
Electron 33 Platform:
Process Architecture:
IPC Communication:
Auto-Update Support:
Packaging Options:
Security Features:
Creating a new Electron application requires running the create-electron-app command with the vite-typescript template. Install electron-builder as a development dependency for packaging. Add electron-updater as a runtime dependency for auto-update functionality.
For detailed commands and configuration, see reference.md Quick Commands section.
Recommended Directory Layout:
The source directory should contain four main subdirectories:
Main Directory: Contains the main process entry point, IPC handler definitions organized by domain, business logic services, and window management modules
Preload Directory: Contains the preload script entry point and exposed API definitions that bridge main and renderer
Renderer Directory: Contains the web application built with React, Vue, or Svelte, including the HTML entry point and Vite configuration
Shared Directory: Contains TypeScript types and constants shared between main and renderer processes
The project root should include the electron.vite.config.ts for build configuration, electron-builder.yml for packaging options, and resources directory for app icons and assets.
Application Lifecycle Management:
The main process initialization follows a specific sequence. First, enable sandbox globally using app.enableSandbox() to ensure all renderer processes run in isolated environments. Then request single instance lock to prevent multiple app instances from running simultaneously.
Window creation should occur after the app ready event fires. Configure BrowserWindow with security-focused webPreferences including contextIsolation enabled, nodeIntegration disabled, sandbox enabled, and webSecurity enabled. Set the preload script path to expose safe APIs to the renderer.
Handle platform-specific behaviors: on macOS, re-create windows when the dock icon is clicked if no windows exist. On other platforms, quit the application when all windows close.
For implementation examples, see examples.md Main Process Entry Point section.
IPC Type Definition Pattern:
Define an interface that maps channel names to their payload types. Group channels by domain such as file operations, window operations, and storage operations. This enables type checking for both main process handlers and renderer invocations.
Main Process Handler Registration:
Register IPC handlers in a dedicated module that imports from the shared types. Each handler should validate input using a schema validation library such as Zod before processing. Use ipcMain.handle for request-response patterns and return structured results.
Preload Script Implementation:
Create an API object that wraps ipcRenderer.invoke calls for each channel. Use contextBridge.exposeInMainWorld to make this API available in the renderer as window.electronAPI. Include cleanup functions for event listeners to prevent memory leaks.
For complete IPC implementation patterns, see examples.md Type-Safe IPC Implementation section.
Mandatory Security Settings:
Every BrowserWindow must have webPreferences configured with four critical settings. contextIsolation must always be enabled to prevent renderer code from accessing Electron internals. nodeIntegration must always be disabled in renderer processes. sandbox must always be enabled for process-level isolation. webSecurity must never be disabled to maintain same-origin policy enforcement.
Content Security Policy:
Configure session-level CSP headers using webRequest.onHeadersReceived. Restrict default-src to self, script-src to self without unsafe-inline, and connect-src to allowed API domains. This prevents XSS attacks and unauthorized resource loading.
Input Validation:
Every IPC handler must validate inputs before processing. Prevent path traversal attacks by rejecting paths containing parent directory references. Validate file names against reserved characters. Use allowlists for permitted directories when implementing file access.
For security implementation details, see reference.md Security Best Practices section.
Update Service Architecture:
Create an UpdateService class that manages the electron-updater lifecycle. Initialize with the main window reference to enable UI notifications. Configure autoDownload as false to give users control over bandwidth usage.
Event Handling:
Handle update-available events by notifying the renderer and prompting the user for download confirmation. Track download-progress events to display progress indicators. Handle update-downloaded events by prompting for restart.
User Notification Pattern:
Use system dialogs to prompt users when updates are available and when downloads complete. Send events to the renderer for in-app notification display. Support both immediate and deferred installation.
For complete update service implementation, see examples.md Auto-Update Integration section.
Electron Builder Configuration:
Configure the appId with reverse-domain notation for platform registration. Specify productName for display in system UI. Set up platform-specific targets for macOS, Windows, and Linux.
macOS Configuration:
Set category for App Store classification. Enable hardenedRuntime and configure entitlements for notarization. Configure universal builds targeting both x64 and arm64 architectures.
Windows Configuration:
Specify icon path for executable and installer. Configure NSIS installer options including installation directory selection. Set up code signing with appropriate hash algorithms.
Linux Configuration:
Configure category for desktop environment integration. Set up multiple targets including AppImage for universal distribution and deb/rpm for package manager installation.
For complete configuration examples, see reference.md Configuration section.
For comprehensive documentation on advanced topics, see reference.md and examples.md:
Window State Persistence:
Multi-Window Management:
System Tray and Native Menus:
Utility Processes:
Native Module Integration:
Protocol Handlers and Deep Linking:
Performance Optimization:
Common Issues and Solutions:
White Screen on Launch:
Verify the preload script path is correctly configured relative to the built output directory. Check that loadFile or loadURL paths point to existing files. Enable devTools to inspect console errors. Review CSP settings that may block script execution.
IPC Not Working:
Confirm channel names match exactly between main handlers and renderer invocations. Ensure handlers are registered before windows load content. Verify contextBridge usage follows the correct pattern with exposeInMainWorld.
Native Modules Fail:
Run electron-rebuild after npm install to recompile native modules. Match the Node.js version embedded in Electron. Add a postinstall script to automate rebuilding.
Auto-Update Not Working:
Verify the application is code-signed as updates require signing. Check publish configuration in electron-builder.yml. Enable electron-updater logging to diagnose connection issues. Review firewall settings that may block update checks.
Debug Commands:
Rebuild native modules with npx electron-rebuild. Check Electron version with npx electron --version. Enable verbose update logging with DEBUG=electron-updater environment variable.
For complete code examples and configuration templates, see:
For latest documentation, use Context7 to query:
Version: 2.0.0 Last Updated: 2026-01-10 Changes: Restructured to comply with CLAUDE.md Documentation Standards - removed all code examples, converted to narrative text format
Weekly Installs
126
Repository
GitHub Stars
867
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
claude-code96
opencode89
codex89
gemini-cli87
cursor87
antigravity82
Flutter应用架构设计指南:分层结构、数据层实现与最佳实践
4,500 周安装