背景 链接到标题
Electron 是用 Web 技术构建跨平台桌面应用的主流方案。本文记录从零搭建 Electron 项目并通过 electron-builder 构建 macOS 安装包的过程。无需 Apple Developer 账号,构建出的 .dmg 可在本机安装运行。
项目结构 链接到标题
electron-proto/
├── package.json
├── src/
│ ├── main.js # 主进程
│ └── index.html # 渲染页面
└── release/ # 构建产物
配置 链接到标题
package.json 链接到标题
{
"name": "electron-proto",
"version": "1.0.0",
"main": "src/main.js",
"scripts": {
"start": "electron .",
"build:mac": "electron-builder --mac"
},
"devDependencies": {
"electron": "^33.0.0",
"electron-builder": "^25.1.0"
},
"build": {
"appId": "com.electron.proto",
"productName": "ElectronProto",
"directories": {
"output": "release"
},
"mac": {
"category": "public.app-category.utilities",
"target": ["dmg"],
"identity": null
}
}
}
identity: null 是关键——告诉 electron-builder 跳过代码签名,否则没有开发者证书时会构建失败。
主进程 链接到标题
const { app, BrowserWindow } = require('electron')
function createWindow() {
const win = new BrowserWindow({
width: 400,
height: 300,
webPreferences: {
nodeIntegration: false,
contextIsolation: true
}
})
win.loadFile('src/index.html')
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => { app.quit() })
渲染页面 链接到标题
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'">
<title>Electron Proto</title>
</head>
<body>
<h1>Hello Electron</h1>
<p>v<script>document.write(process.versions.electron)</script></p>
</body>
</html>
构建 链接到标题
# 国内网络需设置镜像
ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/" npm install
# 构建 macOS DMG
npm run build:mac
产物在 release/ 目录:
| 文件 | 大小 |
|---|---|
| ElectronProto-1.0.0.dmg | 98 MB |
| ElectronProto-1.0.0.dmg.blockmap | 105 KB |
安装 链接到标题
双击 .dmg 将 app 拖入 Applications 目录。首次运行需右键 → 打开(无签名 app 被 Gatekeeper 拦截时需手动确认)。
注意事项 链接到标题
- 本机安装运行完全正常,但无法分发给其他用户——系统会提示"来自身份不明的开发者"
- 如需分发,需 Apple Developer 账号进行代码签名 + 公证
- 也可通过
xattr -cr /Applications/ElectronProto.app解除隔离属性 - 生产项目建议添加应用图标(
build/icon.icns)