Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

electron-best-practices

БесплатноЗапускает вложенные скриптыНе проверен

Guide AI agents through Electron app development with React including security patterns, type-safe IPC, React integration, packaging with code signing, and…

jwyniaот jwynia★ 195 звёзд на GitHub

Об этом скилле

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

Category Prefer Avoid
Security contextBridge.exposeInMainWorld() nodeIntegration: true
IPC invoke/handle pattern send/on for request-response
Preload Typed function wrappers Exposing raw ipcRenderer
Build tool electron-vite webpack-based toolchains
Packaging Electron Forge Manual packaging
State Zustand + electron-store Redux for simple apps
Testing Playwright E2E Spectron (deprecated)
Updates electron-updater Manual update checks
Signing CI-integrated code signing Unsigned releases
CSP HTTP headers, 'self' only No CSP
Error handling Result type
Полный SKILL.md на GitHub

Установить electron-best-practices в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

assets/configs/electron-vite.config.ts.mdassets/configs/forge.config.js.mdassets/configs/playwright.config.ts.mdassets/configs/tsconfig.json.mdassets/examples/multi-window-example.mdassets/examples/typed-ipc-example.mdassets/templates/ipc-handler.ts.mdassets/templates/main-process.ts.mdassets/templates/preload-script.ts.mdassets/templates/react-root.tsx.mdreferences/architecture/multi-window-state.mdreferences/architecture/process-separation.mdreferences/architecture/project-structure.mdreferences/integration/react-patterns.mdreferences/integration/state-management.mdreferences/ipc/electron-trpc.mdreferences/ipc/error-serialization.mdreferences/ipc/typed-ipc.mdreferences/packaging/auto-updates.mdreferences/packaging/bundle-optimization.mdreferences/packaging/ci-cd-patterns.mdreferences/packaging/code-signing.mdreferences/security/context-isolation.mdreferences/security/csp-and-permissions.mdreferences/security/security-checklist.mdreferences/testing/playwright-e2e.mdreferences/testing/test-structure.mdreferences/testing/unit-testing.mdreferences/tooling/electron-forge.mdreferences/tooling/electron-vite.mdreferences/tooling/tauri-comparison.mdscripts/analyze-security.tsscripts/generate-ipc-types.tsscripts/scaffold-electron-app.ts

FAQ

Что делает скилл electron-best-practices?

Guide AI agents through Electron app development with React including security patterns, type-safe IPC, React integration, packaging with code signing, and testing. Keywords: electron, electron-vite, electron-forge, contextBridge, IPC, security, react, packaging, code signing, notarization, playwright, desktop app.

Как установить скилл electron-best-practices?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл electron-best-practices запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить electron-best-practices с