moai-framework-electron

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Electron 33+ Desktop Development

Electron 33+ 桌面应用开发

Quick Reference

快速参考

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+ 桌面应用开发专家支持使用Web技术构建跨平台桌面应用。
自动触发条件:通过electron.vite.config.ts或electron-builder.yml文件检测到Electron项目、桌面应用开发请求、IPC通信模式实现

Core Capabilities

核心能力

Electron 33 Platform:
  • Chromium 130 rendering engine for modern web features
  • Node.js 20.18 runtime for native system access
  • Native ESM support in main process
  • WebGPU API support for GPU-accelerated graphics
Process Architecture:
  • Main process runs as single instance per application with full Node.js access
  • Renderer processes display web content in sandboxed environments
  • Preload scripts bridge main and renderer with controlled API exposure
  • Utility processes handle background tasks without blocking UI
IPC Communication:
  • Type-safe invoke/handle patterns for request-response communication
  • contextBridge API for secure renderer access to main process functionality
  • Event-based messaging for push notifications from main to renderer
Auto-Update Support:
  • electron-updater integration with GitHub and S3 publishing
  • Differential updates for smaller download sizes
  • Update notification and installation management
Packaging Options:
  • Electron Forge for integrated build tooling and plugin ecosystem
  • electron-builder for flexible multi-platform distribution
Security Features:
  • contextIsolation for preventing prototype pollution
  • Sandbox enforcement for renderer process isolation
  • Content Security Policy configuration
  • Input validation patterns for IPC handlers
Electron 33平台:
  • Chromium 130渲染引擎,支持现代Web特性
  • Node.js 20.18运行时,可访问原生系统
  • 主进程支持原生ESM
  • 支持WebGPU API,用于GPU加速图形
进程架构:
  • 主进程作为每个应用的单实例运行,拥有完整的Node.js访问权限
  • 渲染进程在沙箱环境中显示Web内容
  • Preload脚本(预加载脚本)连接主进程和渲染进程,受控暴露API
  • 实用进程处理后台任务,不阻塞UI
IPC通信:
  • 类型安全的invoke/handle模式,用于请求-响应通信
  • contextBridge API,安全地让渲染进程访问主进程功能
  • 基于事件的消息传递,用于主进程向渲染进程推送通知
自动更新支持:
  • electron-updater集成,支持GitHub和S3发布
  • 差分更新,减小下载包大小
  • 更新通知和安装管理
打包选项:
  • Electron Forge:集成构建工具和插件生态系统
  • electron-builder:灵活的多平台分发
安全特性:
  • contextIsolation:防止原型污染
  • 强制沙箱:隔离渲染进程
  • 内容安全策略配置
  • IPC处理器的输入验证模式

Project Initialization

项目初始化

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.

创建新的Electron应用需要使用vite-typescript模板运行create-electron-app命令。安装electron-builder作为开发依赖用于打包。添加electron-updater作为运行时依赖以实现自动更新功能。
有关详细命令和配置,请参阅reference.md的“快速命令”部分。

Implementation Guide

实现指南

Project Structure

项目结构

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.
推荐目录布局:
源码目录应包含四个主要子目录:
主进程目录:包含主进程入口文件、按领域组织的IPC处理器定义、业务逻辑服务和窗口管理模块
预加载脚本目录:包含预加载脚本入口文件和连接主进程与渲染进程的暴露API定义
渲染进程目录:包含使用React、Vue或Svelte构建的Web应用,包括HTML入口文件和Vite配置
共享目录:包含主进程和渲染进程共享的TypeScript类型和常量
项目根目录应包含用于构建配置的electron.vite.config.ts、用于打包选项的electron-builder.yml,以及用于应用图标和资源的resources目录。

Main Process Setup

主进程设置

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.
应用生命周期管理:
主进程初始化遵循特定顺序。首先,使用app.enableSandbox()全局启用沙箱,确保所有渲染进程在隔离环境中运行。然后请求单实例锁,防止多个应用实例同时运行。
窗口创建应在app ready事件触发后进行。配置BrowserWindow时启用安全相关的webPreferences,包括开启contextIsolation、禁用nodeIntegration、启用sandbox、开启webSecurity。设置预加载脚本路径,向渲染进程暴露安全API。
处理平台特定行为:在macOS上,如果没有窗口存在,点击dock图标时重新创建窗口。在其他平台上,所有窗口关闭时退出应用。
有关实现示例,请参阅examples.md的“主进程入口文件”部分。

Type-Safe IPC Communication

类型安全的IPC通信

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.
IPC类型定义模式:
定义一个接口,将通道名称映射到其负载类型。按领域对通道进行分组,如文件操作、窗口操作和存储操作。这样可以对主进程处理器和渲染进程调用进行类型检查。
主进程处理器注册:
在专用模块中注册IPC处理器,导入共享类型。每个处理器在处理前应使用Zod等模式验证库验证输入。使用ipcMain.handle处理请求-响应模式,并返回结构化结果。
预加载脚本实现:
创建一个API对象,封装每个通道的ipcRenderer.invoke调用。使用contextBridge.exposeInMainWorld将此API作为window.electronAPI提供给渲染进程。包含事件监听器的清理函数,防止内存泄漏。
有关完整的IPC实现模式,请参阅examples.md的“类型安全IPC实现”部分。

Security Best Practices

安全最佳实践

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.
强制安全设置:
每个BrowserWindow必须配置webPreferences的四个关键设置。必须始终启用contextIsolation,防止渲染进程代码访问Electron内部。必须始终在渲染进程中禁用nodeIntegration。必须始终启用sandbox以实现进程级隔离。绝不能禁用webSecurity,以维持同源策略执行。
内容安全策略:
使用webRequest.onHeadersReceived配置会话级CSP头。将default-src限制为self,script-src限制为self且不允许unsafe-inline,connect-src限制为允许的API域名。这可以防止XSS攻击和未授权资源加载。
输入验证:
每个IPC处理器在处理前必须验证输入。通过拒绝包含父目录引用的路径,防止路径遍历攻击。验证文件名是否包含保留字符。实现文件访问时,使用允许列表指定允许的目录。
有关安全实现细节,请参阅reference.md的“安全最佳实践”部分。

Auto-Update Implementation

自动更新实现

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.
更新服务架构:
创建UpdateService类,管理electron-updater的生命周期。使用主窗口引用初始化,以启用UI通知。将autoDownload配置为false,让用户控制带宽使用。
事件处理:
处理update-available事件,通知渲染进程并提示用户确认下载。跟踪download-progress事件以显示进度指示器。处理update-downloaded事件,提示用户重启。
用户通知模式:
使用系统对话框在更新可用和下载完成时提示用户。向渲染进程发送事件以显示应用内通知。支持立即安装和延迟安装。
有关完整的更新服务实现,请参阅examples.md的“自动更新集成”部分。

App Packaging

应用打包

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.

Electron Builder配置:
使用反向域名符号配置appId,用于平台注册。指定productName,在系统UI中显示。为macOS、Windows和Linux设置平台特定的目标。
macOS配置:
设置category用于App Store分类。启用hardenedRuntime并配置entitlements用于公证。配置通用构建,同时支持x64和arm64架构。
Windows配置:
指定可执行文件和安装程序的图标路径。配置NSIS安装程序选项,包括安装目录选择。使用适当的哈希算法设置代码签名。
Linux配置:
配置category用于桌面环境集成。设置多个目标,包括用于通用分发的AppImage和用于包管理器安装的deb/rpm。
有关完整的配置示例,请参阅reference.md的“配置”部分。

Advanced Patterns

高级模式

For comprehensive documentation on advanced topics, see reference.md and examples.md:
Window State Persistence:
  • Saving and restoring window position and size across sessions
  • Handling multiple displays and display changes
  • Managing maximized and fullscreen states
Multi-Window Management:
  • Creating secondary windows with proper parent-child relationships
  • Sharing state between multiple windows
  • Coordinating window lifecycle events
System Tray and Native Menus:
  • Creating and updating system tray icons with context menus
  • Building application menus with keyboard shortcuts
  • Platform-specific menu patterns for macOS and Windows
Utility Processes:
  • Spawning utility processes for CPU-intensive background tasks
  • Communicating with utility processes via MessageChannel
  • Managing utility process lifecycle and error handling
Native Module Integration:
  • Rebuilding native modules for Electron Node.js version
  • Using better-sqlite3 for local database storage
  • Integrating keytar for secure credential storage
Protocol Handlers and Deep Linking:
  • Registering custom URL protocols for app launching
  • Handling deep links on different platforms
  • OAuth callback handling via custom protocols
Performance Optimization:
  • Lazy loading windows and heavy modules
  • Optimizing startup time with deferred initialization
  • Memory management for long-running applications

有关高级主题的全面文档,请参阅reference.md和examples.md:
窗口状态持久化:
  • 保存和恢复跨会话的窗口位置和大小
  • 处理多显示器和显示器变化
  • 管理最大化和全屏状态
多窗口管理:
  • 创建具有正确父子关系的次级窗口
  • 在多个窗口之间共享状态
  • 协调窗口生命周期事件
系统托盘和原生菜单:
  • 创建和更新带有上下文菜单的系统托盘图标
  • 构建带有键盘快捷键的应用菜单
  • macOS和Windows的平台特定菜单模式
实用进程:
  • 生成实用进程处理CPU密集型后台任务
  • 通过MessageChannel与实用进程通信
  • 管理实用进程的生命周期和错误处理
原生模块集成:
  • 为Electron Node.js版本重新构建原生模块
  • 使用better-sqlite3进行本地数据库存储
  • 集成keytar进行安全凭证存储
协议处理器和深度链接:
  • 注册自定义URL协议以启动应用
  • 在不同平台上处理深度链接
  • 通过自定义协议处理OAuth回调
性能优化:
  • 懒加载窗口和重型模块
  • 通过延迟初始化优化启动时间
  • 长期运行应用的内存管理

Works Well With

协同工具

  • moai-lang-typescript - TypeScript patterns for type-safe Electron development
  • moai-domain-frontend - React, Vue, or Svelte renderer development
  • moai-lang-javascript - Node.js patterns for main process
  • moai-domain-backend - Backend API integration
  • moai-workflow-testing - Testing strategies for desktop apps

  • moai-lang-typescript - 用于类型安全Electron开发的TypeScript模式
  • moai-domain-frontend - React、Vue或Svelte渲染进程开发
  • moai-lang-javascript - 主进程的Node.js模式
  • moai-domain-backend - 后端API集成
  • moai-workflow-testing - 桌面应用的测试策略

Troubleshooting

故障排除

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.

常见问题及解决方案:
启动时白屏:
验证预加载脚本路径相对于构建输出目录的配置是否正确。检查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环境变量启用详细的更新日志。

Resources

资源

For complete code examples and configuration templates, see:
  • reference.md - Detailed API documentation, version matrix, Context7 library mappings
  • examples.md - Production-ready code examples for all patterns
For latest documentation, use Context7 to query:
  • /electron/electron for core Electron APIs
  • /electron/forge for Electron Forge tooling
  • /electron-userland/electron-builder for packaging configuration

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
有关完整的代码示例和配置模板,请参阅:
  • reference.md - 详细的API文档、版本矩阵、Context7库映射
  • examples.md - 所有模式的生产级代码示例
如需最新文档,使用Context7查询:
  • /electron/electron - 核心Electron API
  • /electron/forge - Electron Forge工具
  • /electron-userland/electron-builder - 打包配置

版本:2.0.0 最后更新:2026-01-10 变更:重构以符合CLAUDE.md文档标准 - 移除所有代码示例,转换为叙述文本格式