electron-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseelectron-builder
electron-builder
Docs: https://www.electron.build (v26.8.x)
Repo: https://github.com/electron-userland/electron-builder
Quick Start
快速开始
Install:
bash
pnpm add electron-builder -D
pnpm add electron-updater # If using auto-updatesMinimal config ():
electron-builder.ymlyaml
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: githubBuild scripts in :
package.jsonjson
{
"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.ymlyaml
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: githubpackage.jsonjson
{
"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 publishbash
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):
- >
package.jsonkey"build" - (default, recommended)
electron-builder.yml - /
electron-builder.json/.json5.toml - /
electron-builder.config.js.ts - CLI:
--config <path>
Do NOT name JS config — conflicts with package name.
electron-builder.jsFor full configuration options, file patterns, macros, icons, and directory settings:
See references/configuration.md
配置文件加载顺序(按优先级从高到低):
- >
package.json字段"build" - (默认推荐)
electron-builder.yml - /
electron-builder.json/.json5.toml - /
electron-builder.config.js.ts - CLI参数:
--config <path>
请勿将JS配置文件命名为 — 会和包名产生冲突。
electron-builder.js完整的配置项、文件匹配规则、宏、图标和目录设置请查看:
references/configuration.md
Essential Config Properties
核心配置属性
| Property | Default | Description |
|---|---|---|
| | Do not change once deployed. Used as bundle ID (macOS) and AUMID (Windows). |
| package.json name | Display name (allows spaces) |
| | |
| | Pack source into asar archive |
| auto | Glob patterns for app source files |
| — | Files copied outside asar (e.g. native addons) |
| — | Files copied to resources directory |
| | Fail build if not signed |
| 属性 | 默认值 | 说明 |
|---|---|---|
| | 部署后请勿修改。 用作macOS的包ID和Windows的AUMID。 |
| package.json中的name字段 | 应用显示名称(支持空格) |
| | 测试构建可使用 |
| | 将源码打包为asar归档 |
| 自动匹配 | 应用源码文件的glob匹配规则 |
| — | 复制到asar外的文件(例如原生扩展) |
| — | 复制到resources目录的文件 |
| | 若签名失败则终止构建 |
File Macros
文件宏
Available in , file patterns, and publish URLs:
, , , , , , , ,
artifactName${arch}${os}${platform}${name}${productName}${version}${channel}${ext}${env.VAR_NAME}可在、文件匹配规则和发布URL中使用:
, , , , , , , ,
artifactName${arch}${os}${platform}${name}${productName}${version}${channel}${ext}${env.VAR_NAME}Default Targets
默认构建目标
| Platform | Default |
|---|---|
| macOS | DMG + ZIP |
| Windows | NSIS |
| Linux (cross) | Snap + AppImage (x64) |
| Linux (native) | Snap + AppImage (current arch) |
| 平台 | 默认目标 |
|---|---|
| macOS | DMG + ZIP |
| Windows | NSIS |
| Linux(交叉构建) | Snap + AppImage(x64架构) |
| Linux(原生构建) | Snap + AppImage(当前架构) |
Code Signing
代码签名
Signing is automatic when configured. Core environment variables:
| Env | Description |
|---|---|
| Certificate path/URL/base64 (.p12/.pfx) |
| Certificate password |
| |
| Windows cert (when cross-signing from macOS) |
| Windows cert password |
配置完成后签名会自动执行。核心环境变量:
| 环境变量 | 说明 |
|---|---|
| 证书路径/URL/base64(.p12/.pfx格式) |
| 证书密码 |
| |
| Windows证书(从macOS交叉构建时使用) |
| Windows证书密码 |
macOS: Disable signing
macOS:关闭签名
bash
export CSC_IDENTITY_AUTO_DISCOVERY=falsebash
export CSC_IDENTITY_AUTO_DISCOVERY=falseOr in config: mac.identity: null
或在配置中添加:mac.identity: null
For ad-hoc (ARM): mac.identity: "-"
ARM架构下临时签名使用:mac.identity: "-"
undefinedundefinedmacOS: Notarization
macOS:应用公证
yaml
mac:
hardenedRuntime: true
notarize: true # or { teamId: "TEAM_ID" }Requires , , env vars.
APPLE_IDAPPLE_APP_SPECIFIC_PASSWORDAPPLE_TEAM_IDyaml
mac:
hardenedRuntime: true
notarize: true # 也可写作 { teamId: "TEAM_ID" }需要配置、、环境变量。
APPLE_IDAPPLE_APP_SPECIFIC_PASSWORDAPPLE_TEAM_IDWindows: 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_IDAZURE_CLIENT_IDAZURE_CLIENT_SECRETFor 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_IDAZURE_CLIENT_IDAZURE_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 — is auto-generated at build time.
setFeedURL()app-update.ymltypescript
// 主进程代码
import electronUpdater, { type AppUpdater } from "electron-updater";
export function getAutoUpdater(): AppUpdater {
const { autoUpdater } = electronUpdater;
return autoUpdater;
}
const autoUpdater = getAutoUpdater();
autoUpdater.checkForUpdatesAndNotify();不要调用 — 会在构建时自动生成。
setFeedURL()app-update.ymlESM 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: draftSet env var (personal access token with scope).
GH_TOKENrepoyaml
publish:
provider: github
releaseType: draft设置环境变量(需拥有权限的个人访问令牌)。
GH_TOKENrepoQuick S3 setup
S3快速配置
yaml
publish:
provider: s3
bucket: my-bucket-nameSet + .
AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYyaml
publish:
provider: s3
bucket: my-bucket-name设置和环境变量。
AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYQuick Generic Server setup
通用服务器快速配置
yaml
publish:
provider: generic
url: https://example.com/releasesUpload artifacts + manually.
latest.ymlyaml
publish:
provider: generic
url: https://example.com/releases手动上传构建产物和到服务器即可。
latest.ymlPublish CLI behavior
发布CLI默认行为
| Condition | Default behavior |
|---|---|
| CI detected | |
| CI + tag pushed | |
npm script | |
| 场景 | 默认行为 |
|---|---|
| 检测到CI环境 | |
| CI环境 + 推送了标签 | |
执行npm的 | |
Release Channels
发布通道
Version determines channel: = , =
1.0.0latest1.0.0-beta.1betaFor all publishers (Bitbucket, GitLab, Keygen, Snap Store, Spaces), workflows, and advanced config:
See references/publishing.md
版本号决定通道:属于通道,属于通道。
1.0.0latest1.0.0-beta.1beta所有发布源(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: trueyaml
mac:
category: public.app-category.developer-tools
hardenedRuntime: true
darkModeSupport: true
target: dmg
entitlements: build/entitlements.mac.plist
notarize: trueWindows (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: trueyaml
nsis:
oneClick: true # 设为false时会显示引导式安装界面
perMachine: false
allowToChangeInstallationDirectory: false
createDesktopShortcut: true
deleteAppDataOnUninstall: false
include: build/installer.nsh # 自定义NSIS脚本
differentialPackage: trueLinux
Linux
yaml
linux:
category: Development
desktop:
MimeType: "x-scheme-handler/myapp"
target:
- AppImage
- deb
- snapFor 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 →
afterAllArtifactBuildInline (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
undefinedyaml
undefinedGitHub 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
undefinedmac:
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
undefinedComplete 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
注意事项
- Never change after release — NSIS uses it for registry GUID
appId - macOS signing required for auto-update to work
- ESM import workaround needed for electron-updater in TypeScript
- Don't call —
setFeedURL()is auto-generatedapp-update.yml - Squirrel.Windows not supported by electron-updater — use NSIS
- Windows env var limit 8192 chars — re-export cert without chain if too large
- conflicts with package name — use different filename
electron-builder.js - Set in main process for Windows notifications
app.setAppUserModelId(appId)
- 发布后绝对不要修改— NSIS会用它生成注册表GUID,修改后会导致升级失败
appId - 自动更新功能要求macOS应用必须完成签名
- TypeScript中使用electron-updater需要使用ESM兼容导入写法
- 不要调用—
setFeedURL()会在构建时自动生成app-update.yml - electron-updater不支持Squirrel.Windows — 请使用NSIS作为Windows构建目标
- Windows环境变量长度限制为8192字符 — 如果证书太大可以导出不带证书链的版本
- 会和包名冲突 — 请使用其他文件名作为JS配置文件
electron-builder.js - 主进程中需要调用才能正常显示Windows通知
app.setAppUserModelId(appId)