Token导航 LogoToken导航TokenDH.com
开发规范操作浏览器github未标认证来源可访问许可证需确认审计通过

electron-best-practicesElectron 最佳实践

Agent Skill

electron-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

11,138

周安装

455

GitHub Stars

69

下载量

3,604
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:electron-best-practices(Electron 最佳实践)
来源仓库:https://github.com/jwynia/agent-skills
仓库路径:skills/electron-best-practices
安装命令:
npx skills add https://github.com/jwynia/agent-skills --skill electron-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/jwynia/agent-skills --skill electron-best-practices

简介

electron-best-practices 提供 Electron + React 项目的安全开发和部署指南。

  • 覆盖 IPC 通信、代码签名、自动更新和性能优化等关键环节。
  • 包含可复用的安全模式和类型生成工具,提升工程规范性。
  • 实施时应遵循最小权限原则,限制不必要的系统访问。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Electron + React Best Practices

Guide AI agents in building secure, production-ready Electron applications with React. This skill provides security patterns, type-safe IPC communication, project setup guidance, packaging and code signing workflows, and tools for analysis, scaffolding, and type generation.

When to Use This Skill

Use this skill when:

  • Generating Electron main, preload, or renderer process code
  • Configuring electron-vite or Electron Forge
  • Setting up IPC communication between processes
  • Implementing security patterns (contextBridge, sandbox, CSP)
  • Packaging, signing, and notarizing desktop applications
  • Testing Electron apps with Playwright
  • Designing multi-window architectures

Do NOT use this skill when:

  • Building Tauri apps (different paradigm, use Tauri-specific guidance)
  • Building pure web apps with no desktop requirements
  • Targeting Electron versions below 20 (security defaults differ)
  • Using non-React renderer frameworks (use framework-specific skills)

Core Principles

1. Security First Architecture

Modern Electron security relies on three defaults that became standard in Electron 20+: context isolation, sandbox mode, and nodeIntegration disabled. Disabling any of them allows XSS attacks to escalate to full remote code execution. All main-renderer communication must flow through contextBridge:

// preload.ts - SECURE pattern
contextBridge.exposeInMainWorld('electronAPI', {
  loadPreferences: () => ipcRenderer.invoke('load-prefs'),
  saveFile: (content: string) => ipcRenderer.invoke('save-file', content),
  onUpdateCounter: (callback: (value: number) => void) => {
    const handler = (_event: IpcRendererEvent, value: number) => callback(value);
    ipcRenderer.on('update-counter', handler);
    return () => ipcRenderer.removeListener('update-counter', handler);
  }
});

Set Content Security Policy via HTTP headers for apps loading local files, restricting script sources to 'self'.

2. Type-Safe IPC Communication

The invoke/handle pattern is preferred over send/on for request-response communication, providing proper async/await semantics and error propagation. For typed channels, use a mapped type pattern:

type IpcChannelMap = {
  'load-prefs': { args: []; return: UserPreferences };
  'save-file': { args: [content: string]; return: { success: boolean } };
};

For complex applications, electron-trpc provides full type safety using tRPC's router pattern with Zod validation:

export const appRouter = t.router({
  greeting: t.procedure
    .input(z.object({ name: z.string() }))
    .query(({ input }) => `Hello, ${input.name}!`),
});

Error handling across the IPC boundary requires attention because Electron only serializes the message property of Error objects. Wrap responses in a {success, data, error} result type to preserve full error context.

3. Modern Project Setup

The recommended stack uses electron-vite for development and Electron Forge for packaging. electron-vite provides a unified configuration managing main, preload, and renderer processes with sub-second dev server startup and instant HMR. Electron Forge uses first-party Electron packages for signing and notarization.

src/
├── main/           # Main process (Node.js environment)
│   ├── index.ts
│   └── ipc/        # IPC handlers
├── preload/        # Secure bridge via contextBridge
│   ├── index.ts
│   └── index.d.ts  # TypeScript declarations for exposed APIs
└── renderer/       # React application (pure web, no Node access)
    ├── src/
    └── index.html

4. React Integration Patterns

React 18's concurrent features work normally in Electron's Chromium-based renderer. Strict Mode's double-invocation of effects catches IPC listener leaks that would otherwise cause memory issues. Always return cleanup functions from effects that register IPC listeners:

useEffect(() => {
  const cleanup = window.electronAPI.onUpdateCounter((value) => {
    setCount(value);
  });
  return cleanup;
}, []);

For multi-window applications, the main process should serve as the single source of truth for shared state. Use electron-store for persistence combined with IPC broadcasting so any window's mutation updates all others.

Quick Reference

CategoryPreferAvoid
SecuritycontextBridge.exposeInMainWorld()nodeIntegration: true
IPCinvoke/handle patternsend/on for request-response
PreloadTyped function wrappersExposing raw ipcRenderer
Build toolelectron-vitewebpack-based toolchains
PackagingElectron ForgeManual packaging
StateZustand + electron-storeRedux for simple apps
TestingPlaywright E2ESpectron (deprecated)
Updateselectron-updaterManual update checks
SigningCI-integrated code signingUnsigned releases
CSPHTTP headers, 'self' onlyNo CSP
Error handlingResult type {success, data, error}Raw Error across IPC
Multi-windowMain process as state hubDirect window-to-window

Code Generation Guidelines

When generating Electron code, follow these patterns:

BrowserWindow Creation

const win = new BrowserWindow({
  webPreferences: {
    preload: path.join(__dirname, '../preload/index.js'),
    contextIsolation: true,
    sandbox: true,
    nodeIntegration: false,
  },
});

Always enable contextIsolation and sandbox. Never enable nodeIntegration. The preload path must resolve to the built output location.

IPC Handler Module

export function registerFileHandlers(): void {
  ipcMain.handle('save-file', async (_event, content: string) => {
    try {
      await fs.writeFile(filePath, content);
      return { success: true, data: filePath };
    } catch (err) {
      return { success: false, error: (err as Error).message };
    }
  });
}

Group related handlers into modules. Use the result type pattern for all return values. Validate all arguments received from the renderer process.

Common Anti-Patterns

Avoid these patterns when generating Electron code:

Anti-PatternProblemSolution
nodeIntegration: trueXSS escalates to full RCEKeep disabled (default)
Exposing ipcRenderer directlyFull IPC access from rendererWrap in contextBridge functions
Missing contextIsolationRenderer accesses preload scopeKeep enabled (default since Electron 12)
No code signingOS security warnings, Gatekeeper blocksSign and notarize for all platforms
BrowserWindow without sandboxPreload has full Node.js accessEnable sandbox (default since Electron 20)
Unvalidated IPC argumentsInjection attacks from rendererValidate with Zod or manual checks
0.0.0.0 server bindingNetwork-exposed local serverAlways bind to 127.0.0.1
Missing CSP headersScript injection vectorsSet strict CSP via HTTP headers
No IPC error serializationLost error context across boundaryUse Result type pattern
Spectron for testingDeprecated, Electron 13 maxUse Playwright

See references/security/security-checklist.md for the full security audit checklist.

Scripts Reference

analyze-security.ts

Analyze Electron projects for security misconfigurations:

deno run --allow-read scripts/analyze-security.ts <path> [options]

Options:
  --strict    Enable all checks
  --json      Output JSON for CI
  -h, --help  Show help

Examples:
  # Analyze a project
  deno run --allow-read scripts/analyze-security.ts ./src

  # Strict mode for CI pipeline
  deno run --allow-read scripts/analyze-security.ts ./src --strict --json

scaffold-electron-app.ts

Scaffold a new Electron + React project with secure defaults:

deno run --allow-read --allow-write scripts/scaffold-electron-app.ts [options]

Options:
  --name <name>     App name (required)
  --path <path>     Target directory (default: ./)
  --with-react      Include React setup
  --with-trpc       Include electron-trpc
  --with-tests      Include Playwright tests

Examples:
  # Basic app with React
  deno run --allow-read --allow-write scripts/scaffold-electron-app.ts \
    --name "my-app" --with-react

  # Full setup with trpc and tests
  deno run --allow-read --allow-write scripts/scaffold-electron-app.ts \
    --name "my-app" --with-react --with-trpc --with-tests

generate-ipc-types.ts

Generate TypeScript type definitions from IPC handler files:

deno run --allow-read --allow-write scripts/generate-ipc-types.ts [options]

Options:
  --handlers <path>  Path to IPC handler files
  --output <path>    Output path for type definitions
  --validate         Validate existing types match handlers

Examples:
  # Generate types from handlers
  deno run --allow-read --allow-write scripts/generate-ipc-types.ts \
    --handlers ./src/main/ipc --output ./src/preload/ipc-types.d.ts

  # Validate types in CI
  deno run --allow-read scripts/generate-ipc-types.ts \
    --handlers ./src/main/ipc --validate

Additional Resources

Security

  • references/security/context-isolation.md - contextBridge and isolation patterns
  • references/security/csp-and-permissions.md - Content Security Policy configuration
  • references/security/security-checklist.md - Full security audit checklist

IPC Communication

  • references/ipc/typed-ipc.md - Typed channel map patterns
  • references/ipc/electron-trpc.md - tRPC integration for full type safety
  • references/ipc/error-serialization.md - Result types across IPC boundary

Architecture

  • references/architecture/project-structure.md - Directory organization
  • references/architecture/process-separation.md - Main, preload, and renderer roles
  • references/architecture/multi-window-state.md - Shared state across windows

React Integration

  • references/integration/react-patterns.md - useEffect cleanup, Strict Mode
  • references/integration/state-management.md - Zustand and electron-store patterns

Packaging & Distribution

  • references/packaging/code-signing.md - Platform-specific signing workflows
  • references/packaging/auto-updates.md - electron-updater configuration
  • references/packaging/bundle-optimization.md - Size reduction techniques
  • references/packaging/ci-cd-patterns.md - GitHub Actions matrix builds

Testing

  • references/testing/playwright-e2e.md - Playwright Electron support
  • references/testing/unit-testing.md - Jest/Vitest multi-project configuration
  • references/testing/test-structure.md - Test organization patterns

Tooling

  • references/tooling/electron-vite.md - Build tool configuration
  • references/tooling/electron-forge.md - Packaging and distribution
  • references/tooling/tauri-comparison.md - When to choose Tauri instead

Templates

  • assets/templates/main-process.ts.md - Main process starter template
  • assets/templates/preload-script.ts.md - Preload script with contextBridge
  • assets/templates/ipc-handler.ts.md - IPC handler module template
  • assets/templates/react-root.tsx.md - React root component template

Configuration Examples

  • assets/configs/electron-vite.config.ts.md - electron-vite configuration
  • assets/configs/forge.config.js.md - Electron Forge configuration
  • assets/configs/tsconfig.json.md - TypeScript configuration presets
  • assets/configs/playwright.config.ts.md - Playwright Electron test config

Complete Examples

  • assets/examples/typed-ipc-example.md - End-to-end typed IPC walkthrough
  • assets/examples/multi-window-example.md - Multi-window state management

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.4%
按下载量换算1,204

Claude

32.56%
按下载量换算1,173

Cursor

17.43%
按下载量换算628

Gemini CLI

9.87%
按下载量换算356

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills