工程化、CI 与稳定性

本章目标

  • 建立 main / preload / renderer / shared 四层结构,阻止跨层引用。
  • 把类型检查、Lint、单元测试、E2E 接入 CI。
  • 设计包体积、启动时间、内存增量的性能门禁。
  • 建立崩溃监控与 JS 异常上报体系,能定位到具体堆栈。
  • 制定异步编程规范,消除主进程阻塞与死锁隐患。

工程分层

推荐目录:

1src/
2├── main/
3│   ├── index.ts
4│   ├── windows/
5│   ├── ipc/
6│   ├── services/
7│   └── system/
8├── preload/
9│   └── index.ts
10├── renderer/
11│   ├── index.html
12│   ├── main.tsx
13│   └── pages/
14└── shared/
15    ├── ipc.ts
16    ├── constants.ts
17    └── types.ts

规则:

  1. renderer 不能 import main 或 Node 内置模块。
  2. preload 只做桥接、参数校验、错误转换,不写业务。
  3. main 不 import renderer 的 UI 代码。
  4. shared 只放类型、常量、纯函数,不能有副作用。
  5. 用 ESLint 的 no-restricted-imports 强制边界。
1{
2  "overrides": [
3    {
4      "files": ["src/renderer/**/*"],
5      "rules": {
6        "no-restricted-imports": [
7          "error",
8          {
9            "patterns": [
10              { "group": ["electron", "node:*", "../main/*"], "message": "renderer 只能通过 preload API 访问主进程" }
11            ]
12          }
13        ]
14      }
15    }
16  ]
17}

TypeScript 与构建

三个进程的运行时环境不同,建议分别构建:

目标模块格式目标环境构建工具
mainCJS/ESMNode(Electron 内置)tsc / esbuild / Vite
preloadCJS沙箱 preloadesbuild / Vite
rendererESMChromiumVite / Webpack
1// tsconfig.json
2{
3  "compilerOptions": {
4    "target": "ES2022",
5    "module": "ESNext",
6    "moduleResolution": "Bundler",
7    "strict": true,
8    "noUncheckedIndexedAccess": true,
9    "noImplicitOverride": true,
10    "exactOptionalPropertyTypes": true,
11    "skipLibCheck": true,
12    "baseUrl": ".",
13    "paths": {
14      "@shared/*": ["src/shared/*"]
15    }
16  }
17}

CI 中至少执行:

1npx tsc --noEmit
2npx eslint . --max-warnings=0

测试策略

层级工具覆盖内容
单元测试Vitestshared 纯函数、数据转换、校验逻辑
主进程集成Vitest + mock electronIPC handler、服务层
E2EPlaywright _electron启动、窗口、关键用户路径
冒烟测试打包产物启动安装包能否启动、版本号、基础页面

Playwright Electron 示例

1// e2e/smoke.spec.ts
2import { test, expect, _electron as electron } from '@playwright/test';
3
4test('应用可以启动并显示主窗口', async () => {
5  const app = await electron.launch({ args: ['.'] });
6  const window = await app.firstWindow();
7
8  await expect(window).toHaveTitle(/MyApp/);
9  await expect(window.getByRole('heading', { level: 1 })).toBeVisible();
10
11  await app.close();
12});
1// playwright.config.ts
2import { defineConfig } from '@playwright/test';
3
4export default defineConfig({
5  testDir: './e2e',
6  timeout: 30_000,
7  retries: process.env.CI ? 1 : 0,
8  use: {
9    trace: 'retain-on-failure',
10  },
11});

E2E 要跑在打包后的产物上,而不是开发服务器,才能覆盖 asar、路径、原生模块等真实差异。

CI/CD 流水线

关键原则:

  • 缓存 node_modules 与构建产物,但避免缓存签名材料。
  • 签名密钥放在 Secret Manager,按环境隔离。
  • 构建产物可复现:锁定依赖版本、固定 Node/Electron 版本。
  • 性能门禁失败要阻断发布,而不是只发告警。

性能门禁

指标与阈值

指标采集方式门禁示例
安装包体积构建产物 stat超过基线 5% 失败
app.asar 体积du/asar list超过基线 3% 失败
冷启动到首屏自动化脚本埋点P95 超过 1.2s 失败
内存峰值启动后固定操作序列采样超过基线 10% 失败
首屏 JS 体积bundle 分析超过预算失败

体积门禁脚本

1// scripts/check-size.ts
2import fs from 'node:fs';
3import path from 'node:path';
4
5type SizeReport = {
6  installerBytes: number;
7  asarBytes: number;
8};
9
10const baselinePath = path.join(process.cwd(), 'perf/size-baseline.json');
11const baseline: SizeReport = JSON.parse(fs.readFileSync(baselinePath, 'utf-8'));
12
13const current: SizeReport = {
14  installerBytes: fs.statSync(process.env.INSTALLER_PATH!).size,
15  asarBytes: fs.statSync(process.env.ASAR_PATH!).size,
16};
17
18const LIMITS = {
19  installerBytes: 1.05,
20  asarBytes: 1.03,
21};
22
23let failed = false;
24
25for (const key of Object.keys(LIMITS) as Array<keyof SizeReport>) {
26  const ratio = current[key] / baseline[key];
27  const limit = LIMITS[key];
28  console.log(`${key}: ${baseline[key]} -> ${current[key]} (${(ratio * 100).toFixed(1)}%)`);
29  if (ratio > limit) {
30    console.error(`${key} 超过门禁 ${(limit * 100).toFixed(0)}%`);
31    failed = true;
32  }
33}
34
35process.exit(failed ? 1 : 0);

启动耗时采集

开发阶段可以在主进程与渲染进程打点:

1// main
2const t0 = performance.now();
3app.whenReady().then(() => {
4  const t1 = performance.now();
5  console.log('main ready', t1 - t0);
6});

生产环境应使用 app.getAppMetrics()、performance API 与自定义上报组合,并把结果按版本、平台、设备分桶。具体方案见启动性能优化。

崩溃监控

主进程崩溃与渲染进程崩溃

启用 crashReporter

1// src/main/index.ts
2import { app, crashReporter } from 'electron';
3
4app.whenReady().then(() => {
5  crashReporter.start({
6    productName: 'MyApp',
7    companyName: 'Example',
8    submitURL: 'https://crash.example.com/submit',
9    uploadToServer: true,
10    compress: true,
11    extra: {
12      version: app.getVersion(),
13    },
14  });
15});

如果使用自建上报,可以关闭自动上传,手动收集:

1crashReporter.start({
2  productName: 'MyApp',
3  companyName: 'Example',
4  submitURL: '',
5  uploadToServer: false,
6});
7
8const lastCrash = crashReporter.getLastCrashReport();
9console.log(lastCrash?.date, lastCrash?.id);
10console.log(app.getPath('crashDumps'));

符号化

崩溃堆栈只有配合符号表才能读:

平台符号来源
macOSdSYM原生模块与自建 Electron 构建
WindowsPDB原生模块与自建 Electron 构建
Electron 自身官方 symbolsElectron 发布页 的 symbols 包

流程:

  1. CI 构建时归档 dSYM/PDB。
  2. 上传到符号服务器(Sentry、Crashpad symbol server、自建对象存储)。
  3. 收到 minidump 后按模块版本匹配符号。
  4. 聚合相同堆栈,按版本/平台统计崩溃率。

渲染进程崩溃上报

1win.webContents.on('render-process-gone', (_event, details) => {
2  reportCrash({
3    type: 'renderer-gone',
4    reason: details.reason,
5    exitCode: details.exitCode,
6    url: win.webContents.getURL(),
7    version: app.getVersion(),
8  });
9});

JS 异常

1// 主进程
2process.on('uncaughtException', (error) => {
3  reportError({ type: 'main-uncaught', error: serializeError(error) });
4});
5
6process.on('unhandledRejection', (reason) => {
7  reportError({ type: 'main-unhandled-rejection', reason: String(reason) });
8});
1// 渲染进程(在入口最早注册)
2window.addEventListener('error', (event) => {
3  window.api.reportError({
4    type: 'renderer-error',
5    message: event.message,
6    stack: event.error?.stack,
7  });
8});
9
10window.addEventListener('unhandledrejection', (event) => {
11  window.api.reportError({
12    type: 'renderer-rejection',
13    message: String(event.reason),
14  });
15});

注意:uncaughtException 之后进程状态可能已损坏,不要继续执行关键逻辑,应尽快上报并退出。

异步编程规范

主进程的异步问题通常来自三类:

1. 同步 I/O

1// 禁止
2const raw = fs.readFileSync(file, 'utf-8');
3
4// 推荐
5const raw = await fs.readFile(file, 'utf-8');

例外:启动阶段读取极小配置文件可以接受,但要测量耗时。

2. 无上限并发

1// 1000 个任务同时发起,可能打满文件句柄
2await Promise.all(files.map((f) => process(f)));
3
4// 限制并发
5import pLimit from 'p-limit';
6const limit = pLimit(8);
7await Promise.all(files.map((f) => limit(() => process(f))));

3. 没有超时与取消

1async function withTimeout<T>(task: Promise<T>, ms: number): Promise<T> {
2  const controller = new AbortController();
3  const timer = setTimeout(() => controller.abort(), ms);
4  try {
5    return await Promise.race([
6      task,
7      new Promise<never>((_, reject) => {
8        controller.signal.addEventListener('abort', () => reject(new Error('timeout')));
9      }),
10    ]);
11  } finally {
12    clearTimeout(timer);
13  }
14}

死锁与相互等待

典型死锁:

1// 渲染进程同步等待主进程
2const result = ipcRenderer.sendSync('data:get');
3
4// 主进程在处理 data:get 时又同步等待渲染进程返回
5ipcMain.on('data:get', (event) => {
6  event.returnValue = rendererMustRespond(); // 永远等不到
7});

避免方式:

  1. 禁用 sendSync。
  2. 主进程的 handler 不要依赖调用方同步返回。
  3. 任何跨进程调用都设置超时。
  4. 异步任务使用请求 ID 关联,避免全局「等待中」状态。

日志体系

1// src/main/logger.ts
2import log from 'electron-log/main';
3
4log.initialize();
5log.transports.file.level = 'info';
6log.transports.console.level = process.env.NODE_ENV === 'development' ? 'debug' : 'warn';
7
8export const logger = log.scope('main');

规范:

  • 分级:error / warn / info / debug。
  • 结构化字段:模块、用户 ID(脱敏)、版本、平台。
  • 敏感信息脱敏:路径、Token、手机号、邮箱。
  • 日志轮转与体积上限。
  • 用户可一键导出日志包,便于支持排障。

发布与回滚

  • 版本号遵循 SemVer,构建号独立。
  • 灰度发布:按用户分桶,先 1% → 10% → 50% → 100%。
  • 崩溃率、启动失败率超过阈值自动停止放量。
  • 保留上一个稳定版本,服务端可回退更新元数据。
  • 协议、数据格式变更要向前兼容,避免旧版本无法启动。

本章小结

  • 四层结构 + ESLint 边界规则,是控制 Electron 工程复杂度的基础。
  • CI 应覆盖类型、Lint、单测、E2E、性能门禁、签名与发布。
  • 性能门禁要把体积、启动、内存变成可比较的数字,而不是主观感觉。
  • 崩溃监控需要 minidump + 符号表 + 聚合分析,缺一不可。
  • 异步规范的核心是:不阻塞主进程、限制并发、设置超时、避免同步 IPC。

参考资料