360 Secure SkillHub
360 安全技能中心

nextjs-to-electron

针对可静态导出的 Next.js App Router 项目,提供 Electron 主进程、自定义协议、窗口状态、托盘和打包配置模板,并指导 CI、Windows 打包与离线环境验证。

分类:开发
rockbenben
rockbenben
热度 66.70
最近更新 2026-12-02 14:02:20

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add rockbenben/nextjs-to-electron
兼容性
通用兼容
联网要求
需要联网
数据出网
数据不出本机
Metadata
name
nextjs-to-electron
description
Convert a static-exportable Next.js App Router app to Windows Electron, including offline targets without WebView2. 将 Next.js 静态导出打包为 Windows 桌面应用。
metadata
{"version":"1.1.20","openclaw":{"homepage":"https://github.com/rockbenben/aishort-skills/tree/main/skills/nextjs-to-electron","emoji":"⚛️","requires":{"bins":["node"]},"files":["electron-files.md"]}}

Next.js → Windows Electron Desktop App

Wrap a static-exportable Next.js (App Router) app in a thin Windows Electron shell (bundled Chromium — no system WebView2, suited for LTSC/Server or air-gapped intranet boxes). All copy-paste code and workflow templates live in electron-files.md.

Core principle: Serve out/ over a custom app:// protocol, never file:// (gotcha #1). Keep shell code inside electron/ and preserve existing web behavior.

Guardrails & Scope

  • Static-export gate: Confirm the desktop routes work from output: "export". Keep build-time Server Components and static GET handlers. Request-time rendering, API handlers that need a running Next.js server, or Server Actions require a separate server design. The packaging templates target Windows. Static-export support
  • Skill boundaries: Use desktop-app-standard for existing Electron apps and nextjs-to-tauri when Tauri is the intended shell.
  • Authorization & read-only mode: Read-only assessments report blockers and proposed checks without installing or building. Migration tasks authorize necessary local config/source changes; remote tags, public releases, and code-signing setup require explicit user scope.
  • Toolchain compatibility: Confirm target Windows version/arch against a supported stable Electron line and compatible electron-builder (Electron releases). In CI, pin an Active LTS Node major (Node schedule); set engines.node from actual tool compatibility, not by copying the CI major.
  • Package manager: Commands assume Yarn Classic; for npm/pnpm substitute lockfile install commands (npm ci / pnpm install --frozen-lockfile) and match setup-node's cache: to the real lockfile (cache: yarn fails without yarn.lock).

Procedure

  1. Verify static export & layout: Configure the desktop build with output: "export" and images.unoptimized: true, or retain an export-compatible image loader. If the web build uses different settings, enable these only for the desktop build and use that same build command in packaging. Inspect out/ for the actual launch page and _next/ assets. For out/index.html the template starts at /. For a locale-only export, pass the shipped default locale to startUrl(store, defaultLocale) in main.js and populate LOCALES from the exported routes.

  2. Install toolchain & configure package.json: Run yarn add -D electron electron-builder (for Electron ≥ 42, also run node node_modules/electron/install.js or yarn run install-electron if the binary is not downloaded at install time). Add "main": "electron/main.js" and scripts:

    • electron:dev: node scripts/electron-dev.cjs launches the shell. Start the Next dev server separately and match its URL to the one in main.js.
    • electron:build: next build && electron-builder --win dir
    • test:electron: list test files explicitly (node --test electron/resolvePath.test.js electron/store.test.js electron/locale.test.js electron/window-state.test.js, gotcha #5)
    • Add electron/package.json ({"type":"commonjs"}) so the shell and tests work even if the root package.json uses "type": "module".
  3. Create the electron/ layer from electron-files.md, keeping pure modules free of require("electron") so node --test runs them directly:

    • Pure modules + unit tests: constants.js, resolvePath.js (.html → /index.html → 404.html + traversal guard), store.js, locale.js, window-state.js.
    • Electron-bound modules: protocol.js, tray.js, main.js.
  4. Register app:// & harden renderer: Register scheme privileges before ready, install protocol.handle after ready, and load startUrl(store). Keep contextIsolation: true, sandbox: true, and nodeIntegration: false.

  5. Wire desktop lifecycle in main.js via passive main-process events (gotchas #3–#4, #8–#9): single-instance lock + second-instance refocus, persisted window bounds, trackLocale(win, store) on navigation, and tray with app.isQuitting close-to-tray fallback.

  6. Configure packaging (electron-builder.yml & .gitignore): Map extraResources (out → out, build/icon.png → icon.png) matching process.resourcesPath when packaged (gotcha #6). Prefer target: dir (fast startup unpacked folder) over portable (re-extracts to %TEMP% every launch, gotcha #11).

  7. Adapt CI workflow from electron-files.md to the actual lockfile, Action pins, and Node version. Tag runs inject the tag version before build, create/reuse a unique draft, verify the ZIP, SHA256, and source commit, then publish; manual runs upload artifacts only. For side branches or multi-app repos, follow its full-SHA source-map/coordinator variant without overwriting an existing Tauri workflow or bypassing asset verification.

  8. Verify & deliver per the section below, keeping pure-module test results distinct from native Windows execution.

Verification & Delivery

Run yarn test:electron and yarn electron:build, then launch the unpacked Windows .exe to exercise rendering, offline assets (do not assume CI network access proves offline behavior), locale persistence, window bounds, single-instance refocus, tray close/reopen, actual quit, and WebView2-less execution when required.

Deliver the runnable package, tests and UI checks actually performed, measured asset sizes, signing status, and any unverified environment limits.

Gotchas

Template comments in electron-files.md reference these numbers — keep numbering intact.

# Symptom Check
1 White screen or unstyled page file:// resolves /_next/... at filesystem root; serve over app:// (also gives storage a stable origin).
2 Flat export route 404 Keep .html → /index.html → 404.html fallback and exact locale matching (zh-hant ≠ zh).
3 Locale resets on launch Static export has no middleware; start at saved locale and persist navigation in main-process store.
4 Desktop integration breaks web Use passive main-process events; add narrow, guarded preload/IPC only if strictly required.
5 Tests import Electron or find 0 cases Keep pure modules Electron-free; list test files explicitly unless Node/shell glob support is verified.
6 Dev works, packaged app fails Match extraResources to process.resourcesPath; keep the full unpacked folder and verify .gitignore doesn't hide build/icon.png.
7 Fonts hang offline Self-host runtime fonts (next/font/google fetches at build time, so build env still needs network).
8 Tray disappears or app won't quit Retain the Tray reference and keep app.isQuitting + failed-tray quit fallback in main.js.
9 Second launch opens duplicate window Verify requestSingleInstanceLock() and second-instance restore/show/focus path.
10 Manual workflow button missing Keep workflow on default branch for manual dispatch and inside each tagged release commit.
11 Slow portable startup / SmartScreen warning Prefer target: dir over portable; disclose signing state (a cert alone does not guarantee SmartScreen bypass).
12 Empty release or mismatched version Build the tag (or committed full source SHA), derive version/asset names from tag, and verify assets before publishing.