electron-builder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

electron-builder

electron-builder

Quick Start

快速开始

Install:
bash
pnpm add electron-builder -D
pnpm add electron-updater  # If using auto-updates
Minimal config (
electron-builder.yml
):
yaml
appId: com.example.myapp
productName: My App
files:
  - "out/**/*"
  - "package.json"
mac:
  target: dmg
  category: public.app-category.developer-tools
win:
  target: nsis
linux:
  target:
    - AppImage
    - deb
publish:
  provider: github
Build scripts in
package.json
:
json
{
  "scripts": {
    "build:mac": "electron-builder --mac",
    "build:win": "electron-builder --win",
    "build:linux": "electron-builder --linux",
    "build:all": "electron-builder -mwl",
    "release": "electron-builder --publish always"
  }
}
安装:
bash
pnpm add electron-builder -D
pnpm add electron-updater  # 如果需要使用自动更新功能
最简配置(
electron-builder.yml
):
yaml
appId: com.example.myapp
productName: My App
files:
  - "out/**/*"
  - "package.json"
mac:
  target: dmg
  category: public.app-category.developer-tools
win:
  target: nsis
linux:
  target:
    - AppImage
    - deb
publish:
  provider: github
package.json
中的构建脚本:
json
{
  "scripts": {
    "build:mac": "electron-builder --mac",
    "build:win": "electron-builder --win",
    "build:linux": "electron-builder --linux",
    "build:all": "electron-builder -mwl",
    "release": "electron-builder --publish always"
  }
}

CLI Reference

CLI参考

bash
electron-builder                    # Build for current platform
electron-builder -mwl              # Build for all platforms
electron-builder --mac dmg         # macOS DMG only
electron-builder --win nsis:ia32   # Windows NSIS 32-bit
electron-builder --linux deb tar.xz
electron-builder --dir             # Unpacked dir (test builds)
electron-builder -p always         # Build and publish
bash
electron-builder                    # 为当前平台构建
electron-builder -mwl              # 为全平台构建
electron-builder --mac dmg         # 仅构建macOS DMG包
electron-builder --win nsis:ia32   # 构建Windows 32位NSIS安装包
electron-builder --linux deb tar.xz
electron-builder --dir             # 生成未打包目录(用于测试构建)
electron-builder -p always         # 构建并发布

Architecture flags

架构参数

--x64 --ia32 --armv7l --arm64 --universal
--x64 --ia32 --armv7l --arm64 --universal

CLI config overrides

CLI覆盖配置项

-c.extraMetadata.foo=bar -c.mac.identity=null -c.nsis.unicode=false
-c.extraMetadata.foo=bar -c.mac.identity=null -c.nsis.unicode=false

Publish existing artifacts

发布已有的构建产物

electron-builder publish -f dist/*.exe -c electron-builder.yml

Publish flag values: `onTag` | `onTagOrDraft` | `always` | `never`
electron-builder publish -f dist/*.exe -c electron-builder.yml

发布参数可选值:`onTag` | `onTagOrDraft` | `always` | `never`

Configuration

配置

Config locations (checked in order):
  1. package.json
    >
    "build"
    key
  2. electron-builder.yml
    (default, recommended)
  3. electron-builder.json
    /
    .json5
    /
    .toml
  4. electron-builder.config.js
    /
    .ts
  5. CLI:
    --config <path>
Do NOT name JS config
electron-builder.js
— conflicts with package name.
For full configuration options, file patterns, macros, icons, and directory settings: See references/configuration.md
配置文件加载顺序(按优先级从高到低):
  1. package.json
    >
    "build"
    字段
  2. electron-builder.yml
    (默认推荐)
  3. electron-builder.json
    /
    .json5
    /
    .toml
  4. electron-builder.config.js
    /
    .ts
  5. CLI参数:
    --config <path>
请勿将JS配置文件命名为
electron-builder.js
— 会和包名产生冲突。
完整的配置项、文件匹配规则、宏、图标和目录设置请查看: references/configuration.md

Essential Config Properties

核心配置属性

PropertyDefaultDescription
appId
com.electron.${name}
Do not change once deployed. Used as bundle ID (macOS) and AUMID (Windows).
productName
package.json nameDisplay name (allows spaces)
compression
"normal"
"store"
for fast test builds,
"maximum"
for release
asar
true
Pack source into asar archive
files
autoGlob patterns for app source files
extraFiles
Files copied outside asar (e.g. native addons)
extraResources
Files copied to resources directory
forceCodeSigning
false
Fail build if not signed
属性默认值说明
appId
com.electron.${name}
部署后请勿修改。 用作macOS的包ID和Windows的AUMID。
productName
package.json中的name字段应用显示名称(支持空格)
compression
"normal"
测试构建可使用
"store"
提升速度,正式发布使用
"maximum"
获得最小体积
asar
true
将源码打包为asar归档
files
自动匹配应用源码文件的glob匹配规则
extraFiles
复制到asar外的文件(例如原生扩展)
extraResources
复制到resources目录的文件
forceCodeSigning
false
若签名失败则终止构建

File Macros

文件宏

Available in
artifactName
, file patterns, and publish URLs:
${arch}
,
${os}
,
${platform}
,
${name}
,
${productName}
,
${version}
,
${channel}
,
${ext}
,
${env.VAR_NAME}
可在
artifactName
、文件匹配规则和发布URL中使用:
${arch}
,
${os}
,
${platform}
,
${name}
,
${productName}
,
${version}
,
${channel}
,
${ext}
,
${env.VAR_NAME}

Default Targets

默认构建目标

PlatformDefault
macOSDMG + ZIP
WindowsNSIS
Linux (cross)Snap + AppImage (x64)
Linux (native)Snap + AppImage (current arch)
平台默认目标
macOSDMG + ZIP
WindowsNSIS
Linux(交叉构建)Snap + AppImage(x64架构)
Linux(原生构建)Snap + AppImage(当前架构)

Code Signing

代码签名

Signing is automatic when configured. Core environment variables:
EnvDescription
CSC_LINK
Certificate path/URL/base64 (.p12/.pfx)
CSC_KEY_PASSWORD
Certificate password
CSC_IDENTITY_AUTO_DISCOVERY
true
/
false
(macOS keychain auto-discovery)
WIN_CSC_LINK
Windows cert (when cross-signing from macOS)
WIN_CSC_KEY_PASSWORD
Windows cert password
配置完成后签名会自动执行。核心环境变量:
环境变量说明
CSC_LINK
证书路径/URL/base64(.p12/.pfx格式)
CSC_KEY_PASSWORD
证书密码
CSC_IDENTITY_AUTO_DISCOVERY
true
/
false
(是否自动发现macOS钥匙串中的证书)
WIN_CSC_LINK
Windows证书(从macOS交叉构建时使用)
WIN_CSC_KEY_PASSWORD
Windows证书密码

macOS: Disable signing

macOS:关闭签名

bash
export CSC_IDENTITY_AUTO_DISCOVERY=false
bash
export CSC_IDENTITY_AUTO_DISCOVERY=false

Or in config: mac.identity: null

或在配置中添加:mac.identity: null

For ad-hoc (ARM): mac.identity: "-"

ARM架构下临时签名使用:mac.identity: "-"

undefined
undefined

macOS: Notarization

macOS:应用公证

yaml
mac:
  hardenedRuntime: true
  notarize: true    # or { teamId: "TEAM_ID" }
Requires
APPLE_ID
,
APPLE_APP_SPECIFIC_PASSWORD
,
APPLE_TEAM_ID
env vars.
yaml
mac:
  hardenedRuntime: true
  notarize: true    # 也可写作 { teamId: "TEAM_ID" }
需要配置
APPLE_ID
APPLE_APP_SPECIFIC_PASSWORD
APPLE_TEAM_ID
环境变量。

Windows: Azure Trusted Signing

Windows:Azure可信签名

yaml
win:
  azureSignOptions:
    publisherName: "CN=Your Company"
    endpoint: "https://eus.codesigning.azure.net"
    certificateProfileName: "your-profile"
    codeSigningAccountName: "your-account"
Requires
AZURE_TENANT_ID
,
AZURE_CLIENT_ID
,
AZURE_CLIENT_SECRET
.
For complete code signing reference (CI setup, certificates, EV certs, cross-platform): See references/code-signing.md
yaml
win:
  azureSignOptions:
    publisherName: "CN=Your Company"
    endpoint: "https://eus.codesigning.azure.net"
    certificateProfileName: "your-profile"
    codeSigningAccountName: "your-account"
需要配置
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
环境变量。
完整的代码签名参考(CI配置、证书、EV证书、跨平台签名)请查看: references/code-signing.md

Auto Update (electron-updater)

自动更新(electron-updater)

Minimal setup

最简配置

typescript
// main process
import electronUpdater, { type AppUpdater } from "electron-updater";

export function getAutoUpdater(): AppUpdater {
  const { autoUpdater } = electronUpdater;
  return autoUpdater;
}

const autoUpdater = getAutoUpdater();
autoUpdater.checkForUpdatesAndNotify();
Do NOT call
setFeedURL()
app-update.yml
is auto-generated at build time.
typescript
// 主进程代码
import electronUpdater, { type AppUpdater } from "electron-updater";

export function getAutoUpdater(): AppUpdater {
  const { autoUpdater } = electronUpdater;
  return autoUpdater;
}

const autoUpdater = getAutoUpdater();
autoUpdater.checkForUpdatesAndNotify();
不要调用
setFeedURL()
app-update.yml
会在构建时自动生成。

ESM Import (required workaround)

ESM导入(需使用兼容写法)

typescript
// CORRECT
import electronUpdater from "electron-updater";
const { autoUpdater } = electronUpdater;

// WRONG (may fail with ESM)
import { autoUpdater } from "electron-updater";
typescript
// 正确写法
import electronUpdater from "electron-updater";
const { autoUpdater } = electronUpdater;

// 错误写法(ESM模式下可能失效)
import { autoUpdater } from "electron-updater";

Auto-updatable targets

支持自动更新的构建目标

  • macOS: DMG
  • Windows: NSIS
  • Linux: AppImage, DEB, Pacman (beta), RPM
macOS apps MUST be signed for auto-update. Squirrel.Windows NOT supported.
  • macOS: DMG
  • Windows: NSIS
  • Linux: AppImage, DEB, Pacman(测试版), RPM
macOS应用必须完成签名才能使用自动更新。不支持Squirrel.Windows。

Events

事件

typescript
autoUpdater.on("error", (err) => {});
autoUpdater.on("checking-for-update", () => {});
autoUpdater.on("update-available", (info) => {});
autoUpdater.on("update-not-available", (info) => {});
autoUpdater.on("download-progress", (progress) => {
  // .bytesPerSecond, .percent, .total, .transferred
});
autoUpdater.on("update-downloaded", (info) => {
  autoUpdater.quitAndInstall();
});
typescript
autoUpdater.on("error", (err) => {});
autoUpdater.on("checking-for-update", () => {});
autoUpdater.on("update-available", (info) => {});
autoUpdater.on("update-not-available", (info) => {});
autoUpdater.on("download-progress", (progress) => {
  // progress包含属性:.bytesPerSecond, .percent, .total, .transferred
});
autoUpdater.on("update-downloaded", (info) => {
  autoUpdater.quitAndInstall();
});

Debugging

调试

typescript
import log from "electron-log";
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = "info";
For staged rollouts, custom updater instances, private repos, dev testing: See references/auto-update.md
typescript
import log from "electron-log";
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = "info";
灰度发布、自定义更新实例、私有仓库、开发测试相关内容请查看: references/auto-update.md

Publishing

发布

Quick GitHub Releases setup

GitHub Releases快速配置

yaml
publish:
  provider: github
  releaseType: draft
Set
GH_TOKEN
env var (personal access token with
repo
scope).
yaml
publish:
  provider: github
  releaseType: draft
设置
GH_TOKEN
环境变量(需拥有
repo
权限的个人访问令牌)。

Quick S3 setup

S3快速配置

yaml
publish:
  provider: s3
  bucket: my-bucket-name
Set
AWS_ACCESS_KEY_ID
+
AWS_SECRET_ACCESS_KEY
.
yaml
publish:
  provider: s3
  bucket: my-bucket-name
设置
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
环境变量。

Quick Generic Server setup

通用服务器快速配置

yaml
publish:
  provider: generic
  url: https://example.com/releases
Upload artifacts +
latest.yml
manually.
yaml
publish:
  provider: generic
  url: https://example.com/releases
手动上传构建产物和
latest.yml
到服务器即可。

Publish CLI behavior

发布CLI默认行为

ConditionDefault behavior
CI detected
onTagOrDraft
CI + tag pushed
onTag
npm script
release
always
场景默认行为
检测到CI环境
onTagOrDraft
CI环境 + 推送了标签
onTag
执行npm的
release
脚本
always

Release Channels

发布通道

Version determines channel:
1.0.0
=
latest
,
1.0.0-beta.1
=
beta
For all publishers (Bitbucket, GitLab, Keygen, Snap Store, Spaces), workflows, and advanced config: See references/publishing.md
版本号决定通道:
1.0.0
属于
latest
通道,
1.0.0-beta.1
属于
beta
通道。
所有发布源(Bitbucket、GitLab、Keygen、Snap Store、Spaces)、工作流和高级配置请查看: references/publishing.md

Platform Target Configuration

平台构建目标配置

macOS

macOS

yaml
mac:
  category: public.app-category.developer-tools
  hardenedRuntime: true
  darkModeSupport: true
  target: dmg
  entitlements: build/entitlements.mac.plist
  notarize: true
yaml
mac:
  category: public.app-category.developer-tools
  hardenedRuntime: true
  darkModeSupport: true
  target: dmg
  entitlements: build/entitlements.mac.plist
  notarize: true

Windows (NSIS)

Windows (NSIS)

yaml
nsis:
  oneClick: true              # false for assisted installer
  perMachine: false
  allowToChangeInstallationDirectory: false
  createDesktopShortcut: true
  deleteAppDataOnUninstall: false
  include: build/installer.nsh  # Custom NSIS script
  differentialPackage: true
yaml
nsis:
  oneClick: true              # 设为false时会显示引导式安装界面
  perMachine: false
  allowToChangeInstallationDirectory: false
  createDesktopShortcut: true
  deleteAppDataOnUninstall: false
  include: build/installer.nsh  # 自定义NSIS脚本
  differentialPackage: true

Linux

Linux

yaml
linux:
  category: Development
  desktop:
    MimeType: "x-scheme-handler/myapp"
  target:
    - AppImage
    - deb
    - snap
For all target options (DMG, PKG, MAS, MSI, AppX, Snap, Flatpak, portable, custom NSIS scripts): See references/platform-targets.md
yaml
linux:
  category: Development
  desktop:
    MimeType: "x-scheme-handler/myapp"
  target:
    - AppImage
    - deb
    - snap
所有构建目标配置(DMG、PKG、MAS、MSI、AppX、Snap、Flatpak、便携版、自定义NSIS脚本)请查看: references/platform-targets.md

Build Hooks

构建钩子

Execution order:
beforeBuild → beforePack → afterExtract → afterPack → [signing] →
afterSign → artifactBuildStarted → [build] → artifactBuildCompleted →
afterAllArtifactBuild
执行顺序:
beforeBuild → beforePack → afterExtract → afterPack → [签名阶段] →
afterSign → artifactBuildStarted → [构建阶段] → artifactBuildCompleted →
afterAllArtifactBuild

Inline (JS/TS config)

内联配置(JS/TS配置文件)

javascript
module.exports = {
  afterSign: async (context) => {
    if (context.electronPlatformName === "darwin") {
      await notarize(context);
    }
  },
  afterAllArtifactBuild: (result) => {
    return ["/path/to/extra/file"];  // Additional files to publish
  },
};
javascript
module.exports = {
  afterSign: async (context) => {
    if (context.electronPlatformName === "darwin") {
      await notarize(context);
    }
  },
  afterAllArtifactBuild: (result) => {
    return ["/path/to/extra/file"];  // 返回需要额外发布的文件路径
  },
};

File reference (YAML config)

文件引用(YAML配置文件)

yaml
beforePack: "./scripts/before-pack.js"
afterSign: "./scripts/notarize.js"
javascript
// scripts/notarize.js
exports.default = async function(context) {
  // context: { outDir, appOutDir, packager, electronPlatformName, arch, targets }
};
For all hooks, context interfaces, and programmatic API: See references/hooks-and-programmatic.md
yaml
beforePack: "./scripts/before-pack.js"
afterSign: "./scripts/notarize.js"
javascript
// scripts/notarize.js
exports.default = async function(context) {
  // context包含属性:{ outDir, appOutDir, packager, electronPlatformName, arch, targets }
};
所有钩子、上下文接口和编程式API请查看: references/hooks-and-programmatic.md

Common Patterns

常用配置示例

Multi-platform CI build

多平台CI构建

yaml
undefined
yaml
undefined

GitHub Actions pattern

GitHub Actions配置示例

mac: target: - target: dmg arch: [x64, arm64] win: target: - target: nsis arch: [x64, ia32] linux: target: - target: AppImage arch: [x64, arm64] - target: deb arch: [x64, arm64] publish: provider: github
undefined
mac: target: - target: dmg arch: [x64, arm64] win: target: - target: nsis arch: [x64, ia32] linux: target: - target: AppImage arch: [x64, arm64] - target: deb arch: [x64, arm64] publish: provider: github
undefined

Complete config with auto-update and signing

包含自动更新和签名的完整配置

yaml
appId: com.example.myapp
productName: My App
copyright: Copyright 2024 Example Inc.
asar: true
compression: normal
forceCodeSigning: true

directories:
  output: dist
  buildResources: build

files:
  - "out/**/*"
  - "package.json"

mac:
  target: [dmg, zip]
  hardenedRuntime: true
  notarize: true
  category: public.app-category.developer-tools

win:
  target: nsis

nsis:
  oneClick: false
  perMachine: false
  allowToChangeInstallationDirectory: true

linux:
  target: [AppImage, deb]
  category: Development

publish:
  provider: github

electronUpdaterCompatibility: ">= 2.16"
yaml
appId: com.example.myapp
productName: My App
copyright: Copyright 2024 Example Inc.
asar: true
compression: normal
forceCodeSigning: true

directories:
  output: dist
  buildResources: build

files:
  - "out/**/*"
  - "package.json"

mac:
  target: [dmg, zip]
  hardenedRuntime: true
  notarize: true
  category: public.app-category.developer-tools

win:
  target: nsis

nsis:
  oneClick: false
  perMachine: false
  allowToChangeInstallationDirectory: true

linux:
  target: [AppImage, deb]
  category: Development

publish:
  provider: github

electronUpdaterCompatibility: ">= 2.16"

Gotchas

注意事项

  1. Never change
    appId
    after release — NSIS uses it for registry GUID
  2. macOS signing required for auto-update to work
  3. ESM import workaround needed for electron-updater in TypeScript
  4. Don't call
    setFeedURL()
    app-update.yml
    is auto-generated
  5. Squirrel.Windows not supported by electron-updater — use NSIS
  6. Windows env var limit 8192 chars — re-export cert without chain if too large
  7. electron-builder.js
    conflicts with package name — use different filename
  8. Set
    app.setAppUserModelId(appId)
    in main process for Windows notifications
  1. 发布后绝对不要修改
    appId
    — NSIS会用它生成注册表GUID,修改后会导致升级失败
  2. 自动更新功能要求macOS应用必须完成签名
  3. TypeScript中使用electron-updater需要使用ESM兼容导入写法
  4. 不要调用
    setFeedURL()
    app-update.yml
    会在构建时自动生成
  5. electron-updater不支持Squirrel.Windows — 请使用NSIS作为Windows构建目标
  6. Windows环境变量长度限制为8192字符 — 如果证书太大可以导出不带证书链的版本
  7. electron-builder.js
    会和包名冲突 — 请使用其他文件名作为JS配置文件
  8. 主进程中需要调用
    app.setAppUserModelId(appId)
    才能正常显示Windows通知