electron

Electron 应用打包与分发

By AI-Writer 13 min read

前言

开发完 Electron 应用后,下一步就是将代码打包成用户可直接安装的程序。Electron 生态中有两个主要的打包工具:electron-builderElectron Forge。本文以 electron-builder 为例,讲解多平台打包配置、自动更新机制、代码签名和 CI/CD 流水线搭建。

electron-builder 基础

安装

bash
pnpm add -D electron-builder

package.json 配置

json
{
  "name": "my-electron-app",
  "version": "1.0.0",
  "productName": "My Electron App",
  "main": "dist/main/index.js",
  "scripts": {
    "build": "vite build && electron-builder",
    "build:win": "vite build && electron-builder --win",
    "build:mac": "vite build && electron-builder --mac",
    "build:linux": "vite build && electron-builder --linux"
  },
  "build": {
    "appId": "com.mycompany.my-electron-app",
    "copyright": "Copyright © 2026 My Company",
    "directories": {
      "output": "release",
      "buildResources": "build"
    },
    "files": [
      "dist/**/*",
      "!node_modules/**/*"
    ],
    "asar": true,
    "win": {
      "target": [
        {
          "target": "nsis",
          "arch": ["x64"]
        }
      ],
      "icon": "build/icon.ico"
    },
    "mac": {
      "category": "public.app-category.productivity",
      "target": [
        {
          "target": "dmg",
          "arch": ["x64", "arm64"]
        }
      ],
      "icon": "build/icon.icns",
      "hardenedRuntime": true,
      "gatekeeperAssess": false
    },
    "linux": {
      "target": ["AppImage", "deb", "rpm"],
      "category": "Utility",
      "icon": "build/icons"
    }
  }
}

常用打包命令

bash
# 打包全平台(Windows / macOS / Linux)
pnpm build

# 只打包 Windows
pnpm build:win

# 打包并发布到 GitHub Releases
pnpm build --win --publish github

Windows 打包配置

NSIS 安装包

NSIS(Nullsoft Scriptable Install System)是 Windows 上最常见的安装程序格式:

json
{
  "win": {
    "target": [
      {
        "target": "nsis",
        "arch": ["x64"]
      },
      {
        "target": "portable",
        "arch": ["x64"]
      }
    ],
    "icon": "build/icon.ico",
    "artifactName": "${productName}-${version}-Setup.${ext}"
  },
  "nsis": {
    "oneClick": false,
    "perMachine": false,
    "allowToChangeInstallationDirectory": true,
    "deleteAppDataOnUninstall": false,
    "installerIcon": "build/icon.ico",
    "uninstallerIcon": "build/icon.ico",
    "installerHeaderIcon": "build/icon.ico",
    "createDesktopShortcut": true,
    "createStartMenuShortcut": true,
    "shortcutName": "My Electron App",
    "runAfterFinish": true,
    "createRepairShortcut": true
  }
}

Windows 打包目标对比

格式说明适用场景
nsis安装向导程序正式分发
portable单文件 exe,无需安装绿色版、便携场景
appxWindows Store 包UWP 应用商店
zipzip 压缩包手动安装

macOS 打包配置

DMG 镜像

json
{
  "mac": {
    "category": "public.app-category.productivity",
    "target": [
      {
        "target": "dmg",
        "arch": ["x64", "arm64"]
      },
      {
        "target": "zip",
        "arch": ["x64", "arm64"]
      }
    ],
    "artifactName": "${productName}-${version}-${arch}.${ext}",
    "icon": "build/icon.icns",
    "hardenedRuntime": true,
    "gatekeeperAssess": false
  },
  "dmg": {
    "title": "${productName} ${version}",
    "background": "build/dmg-background.png",
    "window": {
      "width": 540,
      "height": 380
    },
    "contents": [
      {
        "x": 130,
        "y": 220,
        "type": "file"
      },
      {
        "x": 410,
        "y": 220,
        "type": "link",
        "path": "/Applications"
      }
    ]
  }
}

macOS Universal Binary(双架构)

macOS Silicon (M1/M2) 和 Intel Mac 需要不同架构的二进制:

json
{
  "mac": {
    "target": [
      {
        "target": "dmg",
        "arch": ["x64", "arm64", "universal"]
      }
    ]
  }
}

Linux 打包配置

json
{
  "linux": {
    "target": [
      {
        "target": "AppImage",
        "arch": ["x64"]
      },
      {
        "target": "deb",
        "arch": ["x64"]
      },
      {
        "target": "rpm",
        "arch": ["x64"]
      }
    ],
    "category": "Office",
    "icon": "build/icons",
    "maintainer": "my@email.com",
    "vendor": "My Company"
  }
}

自动更新

electron-builder 配合 electron-updater 可以实现应用内自动更新:

安装依赖

bash
pnpm add electron-updater

主进程配置

typescript
// main.ts — 自动更新配置
import { autoUpdater } from 'electron-updater';
import { BrowserWindow, ipcMain } from 'electron';

// 开启自动下载(发现新版本后自动后台下载)
autoUpdater.autoDownload = true;
autoUpdater.autoInstallOnAppQuit = true;

autoUpdater.on('checking-for-update', () => {
  console.log('检查更新中...');
});

autoUpdater.on('update-available', (info) => {
  console.log('发现新版本:', info.version);
  mainWindow?.webContents.send('update:available', info);
});

autoUpdater.on('update-not-available', () => {
  console.log('已是最新版本');
});

autoUpdater.on('download-progress', (progress) => {
  mainWindow?.webContents.send('update:progress', progress.percent);
});

autoUpdater.on('update-downloaded', (info) => {
  console.log('更新已下载完毕:', info.version);
  mainWindow?.webContents.send('update:downloaded', info);
});

autoUpdater.on('error', (error) => {
  console.error('更新错误:', error);
});

ipcMain.handle('update:check', async () => {
  try {
    return await autoUpdater.checkForUpdates();
  } catch (error) {
    console.error('检查更新失败:', error);
    return null;
  }
});

ipcMain.handle('update:install', () => {
  autoUpdater.quitAndInstall();
});

GitHub Releases 发布

json
// package.json
{
  "build": {
    "publish": [
      {
        "provider": "github",
        "owner": "myusername",
        "repo": "my-electron-app"
      }
    ]
  }
}

在 GitHub 上创建 Releases 并上传 .yml 清单文件后,electron-updater 会自动检查并推送更新。

代码签名

Windows Authenticode 签名

bash
# 安装代码签名工具
# 推荐使用 electron-builder 内置的签名支持

# 方式1:使用证书文件
export WIN_CSC_FILE=/path/to/certificate.pfx
export WIN_CSC_LINK_PASSWORD=证书密码

# 方式2:使用 Azure SignTool(CI 环境推荐)
pnpm build --win --config.winCodeSign.spcFile=./certificate.spc --config.winCodeSign.keyFile=./certificate.pvk

GitHub Actions 中的 Windows 签名配置:

yaml
# .github/workflows/build.yml
- name: Build and sign Windows
  if: github.event_name == 'release'
  env:
    # GitHub Secrets 中配置的证书
    WIN_CSC_FILE: ${{ secrets.WINDOWS_CERTIFICATE }}
    WIN_CSC_LINK_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
  run: pnpm build --win --publish always

macOS Apple Developer 签名

bash
# macOS 代码签名配置
export APPLEID=${{ secrets.APPLE_ID }}
export APPLEIDPASS=${{ secrets.APPLE_ID_PASSWORD }}
export CSC_LINK=${{ secrets.MACOS_CERTIFICATE }}
export CSC_KEY_PASSWORD=${{ secrets.MACOS_CERTIFICATE_PASSWORD }}

Apple Developer 证书类型

  • Developer ID Application:用于 App Store 外分发(推荐)
  • Mac App Store Applications:用于 Mac App Store

ad-hoc 签名(开发测试)

开发阶段可以使用 ad-hoc 签名,无需购买开发者证书,但安装时会显示「来自未知开发者」的警告:

json
{
  "mac": {
    "hardenedRuntime": false,
    "gatekeeperAssess": false
  }
}

GitHub Actions CI/CD 流水线

yaml
# .github/workflows/release.yml
name: Build & Release

on:
  push:
    tags:
      - 'v*'  # 推送 v1.0.0 等标签时触发

jobs:
  release:
    strategy:
      matrix:
        include:
          - os: macos-latest
            platform: darwin
          - os: windows-latest
            platform: win32
          - os: ubuntu-latest
            platform: linux

    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Build
        run: |
          if [ "${{ matrix.platform }}" = "darwin" ]; then
            pnpm build --mac --publish always
          elif [ "${{ matrix.platform }}" = "win32" ]; then
            pnpm build --win --publish always
          else
            pnpm build --linux --publish always
          fi
        env:
          # macOS 代码签名(仅 release 时)
          APPLEID: ${{ secrets.APPLE_ID }}
          APPLEIDPASS: ${{ secrets.APPLE_ID_PASSWORD }}
          CSC_LINK: ${{ secrets.MACOS_CERTIFICATE }}
          CSC_KEY_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
          # Windows 代码签名
          WIN_CSC_FILE: ${{ secrets.WINDOWS_CERTIFICATE }}
          WIN_CSC_LINK_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
          # GitHub Token(自动更新需要)
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.platform }}-build
          path: release/

发布流程

  1. 修改代码,完成开发
  2. git tag v1.0.0 创建标签
  3. git push origin v1.0.0 推送标签
  4. GitHub Actions 自动触发构建、签名和发布
  5. 在 GitHub Releases 页面查看发布的安装包

常见问题

打包后应用图标显示异常

bash
# macOS:生成 .icns 文件
# 1. 准备 1024x1024 PNG
# 2. 使用 iconutil 转换
iconutil -c icns icon.iconset

# Windows:生成 .ico 文件
# 使用 png2icons 或 electron-icon-maker
npm install -g electron-icon-maker
electron-icon-maker --input=icon.png --output=build/

asar 打包后原生模块报错

json
{
  "build": {
    "asar": true,
    "asarUnpack": [
      "**/node_modules/better-sqlite3/**",
      "**/node_modules/sharp/**",
      "**/node_modules/@img/sharp-js/**"
    ]
  }
}

macOS 在 Apple Silicon 上构建 Intel 应用

bash
# 在 M1 Mac 上构建 Intel (x64) 应用
arch -x86_64 pnpm build --mac --x64

小结

  • electron-builder 支持 Windows (NSIS/portable)、macOS (DMG/ZIP)、Linux (AppImage/deb/rpm) 多平台打包
  • electron-updater 配合 GitHub Releases 实现静默自动更新
  • 代码签名是正式发布的必要步骤:Windows 使用 Authenticode,macOS 使用 Apple Developer 证书
  • GitHub Actions 自动化构建流程:推送 Git Tag → CI 构建签名 → 发布 Release
  • 多平台构建建议在对应操作系统的 CI 环境中执行(macOS 构建 macOS,Windows 构建 Windows)

下一篇文章我们将深入 Electron 安全最佳实践,了解 CSP 配置、openExternal 白名单、敏感数据加密存储等关键安全措施。

#electron #electron-builder #打包 #CI/CD #auto-update

评论

A

Written by

AI-Writer

Related Articles

electron
#6

原生对话框与文件操作

使用 dialog.showOpenDialog、showSaveDialog、showMessageBox 原生对话框,Shell 模块打开外部链接和文件资源管理器,跨平台路径处理和用户数据目录访问

Read More
electron
#5

窗口管理与系统交互

掌握 BrowserWindow 高级配置(frame、transparent、kiosk)、多窗口管理、系统托盘 Tray、全局快捷键 globalShortcut,以及屏幕与窗口状态监控

Read More