Electron 打包与分发

electron-builder 配置、三平台产物、图标与签名准备。

Advanced
Key Pointselectron-builder 一条命令产出各平台安装包;签名不是可选项,未签名的应用会被系统拦下。

安装 electron-builder

Bash
npm install --save-dev electron-builder

配置

JSON
{
  "name": "my-app",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "dist": "electron-builder",
    "dist:win": "electron-builder --win",
    "dist:mac": "electron-builder --mac",
    "dist:linux": "electron-builder --linux"
  },
  "build": {
    "appId": "com.example.myapp",
    "productName": "My App",
    "directories": { "output": "release" },
    "files": ["main.js", "preload.js", "dist/**/*", "!**/*.map"],
    "asar": true,
    "win": {
      "target": [{ "target": "nsis", "arch": ["x64"] }],
      "icon": "build/icon.ico"
    },
    "nsis": {
      "oneClick": false,
      "allowToChangeInstallationDirectory": true,
      "createDesktopShortcut": true
    },
    "mac": {
      "target": ["dmg"],
      "icon": "build/icon.icns",
      "category": "public.app-category.productivity"
    },
    "linux": {
      "target": ["AppImage", "deb"],
      "icon": "build/icon.png",
      "category": "Utility"
    }
  }
}

产物

Bash
npm run dist:win
Text
release/
├── My App Setup 1.0.0.exe        ← Windows 安装包
├── My App-1.0.0.AppImage         ← Linux 免安装
├── My App-1.0.0.dmg              ← macOS 磁盘映像
└── win-unpacked/                 ← 解压后的目录版

nsis is the Windows installer wizard, portable a single-file build, AppImage the Linux portable format. End users want installers; internal distribution is easier with portables.

图标

PlatformFormatSize
Windows.ico256×256 起,内含多种尺寸
macOS.icns512×512 起
Linux.png512×512

Prepare a 1024×1024 PNG and let electron-icon-builder generate all three. A bad icon fails packaging with only "invalid icon" as the message.

签名

Bash
# macOS:需要 Apple Developer 证书
export CSC_LINK=/path/to/cert.p12
export CSC_KEY_PASSWORD=yourpassword

# Windows:需要代码签名证书
set CSC_LINK=C:\path\to\cert.pfx
set CSC_KEY_PASSWORD=yourpassword
PlatformUnsigned consequence
WindowsSmartScreen 警告「未知发布者」
macOSGatekeeper 直接拒绝,提示「已损坏」
Linux一般不受限
On macOS an unsigned, un-notarised app shows "the app is damaged and can't be opened" — not a permission prompt, it simply will not launch. Signing plus notarisation is unavoidable.

常见打包问题

  • 产物太大 —— 检查 dependencies 是否混进了开发依赖
  • 白屏 —— files 漏了资源,或用了打包后失效的绝对路径
  • 原生模块报错 —— 需要 electron-rebuild 或 asarUnpack
  • 只出当前平台 —— 交叉编译有限制,最好用 CI 分平台构建
JSON
{
  "build": {
    "asarUnpack": ["**/*.node", "resources/**"]
  }
}

Native modules (.node) cannot load from inside an asar and must be asarUnpacked. Forget it and every call fails with Cannot find module after packaging.

Friends & Partners