不聯網的情況下,使用 electron-builder 快速打包全平臺應用
前言
Electron 之所以能夠日益風靡,是因為其簡單易用且對各個操作平臺具有良好的支援。
今天我就來分享一下怎麼使用一套程式碼,快速打包生成各主流平臺安裝包的經驗。
專案安裝
首先,使用我前面介紹的提效小技巧,設定:
- NPM 源為淘寶映象源;
- Electron 源為中國映象網站中的 Electron 源地址。
然後依次執行以下指令:
mkdir my-electron cd my-electron npm init -y npm install [email protected] -D npm install @electron/remote --save npm install electron-builder -D
打包配置
在 my-electron 目錄下的 package.json 中,新增打包配置:
{ "name": "my-electron", "version": "0.1.0", "author": "程式設計三昧", "build": { // electron-builder配置 "productName":"myFirstApp",//專案名 這也是生成的exe檔案的字首名 "appId": "xxxxx", "copyright":"xxxx",//版權資訊 "directories": { "output": "build" // 輸出資料夾 }, "extraResources": [{ // 需要讀寫的配置檔案 "from": "./config/config.json", "to": "../config/config.json" }], "win": { "icon": "xxx/icon.ico"//圖示路徑, "target":[ { "target": "nsis", "arch": ["x64"] } ] }, "dmg": { "contents": [ { "x": 0, "y": 0, "path": "/Application" } ] }, "linux": { "icon": "xxx/icon.ico" }, "mac": { "icon": "xxx/icon.ico" }, "nsis": { "oneClick": false, // 一鍵安裝 "guid": "xxxx", //登錄檔名字,不推薦修改 "perMachine": true, // 是否開啟安裝時許可權限制(此電腦或當前使用者) "allowElevation": true, // 允許請求提升。 如果為false,則使用者必須使用提升的許可權重新啟動安裝程式。 "allowToChangeInstallationDirectory": true, // 允許修改安裝目錄 "installerIcon": "./build/icons/aaa.ico", // 安裝圖示 "uninstallerIcon": "./build/icons/bbb.ico", //解除安裝圖示 "installerHeaderIcon": "./build/icons/aaa.ico", // 安裝時頭部圖示 "createDesktopShortcut": true, // 建立桌面圖示 "createStartMenuShortcut": true, // 建立開始選單圖示 "shortcutName": "xxxx" // 圖示名稱 } } }
配置打包指令碼
在 package.json 中,新增對應的打包指令碼:
{
…
"scripts": {
"dev": "electron . --enable-loggin --no-sandbox",
"build-64": "electron-builder --win --x64",
"build-linux": "electron-builder --linux",
"build-mac": "electron-builder --mac"
}
…
}
在 my-electron 目錄下開啟終端,執行 npm run dev
即可進入開發模式。
關於各平臺 Electron 映象
在有網路的情況下,由於我們設定了 NPM 映象和 Electron 源,速度還是很快的。
但我這邊是內網打包,沒法聯網,所以,需要取個巧,在打包開始之前就將對應平臺的 Electron 源下載下來放到各自的 NPM 快取中去。
electron-builder 在打包的時候,會根據系統的不同去各自的 NPM 快取目錄下查詢對應版本的 Electron 源,當我們將下載好的源放在 NPM 快取中後,就不需要再去聯網拉去了。
我使用的 [email protected] 映象的下載地址為:https://registry.npmmirror.com/binary.html?path=electron/14.2.6/
。
這是 @electron/get
中獲取 electron 映象快取的示例:
import { downloadArtifact } from '@electron/get';
const zipFilePath = await downloadArtifact({
version: '14.2.6',
platform: 'darwin',
artifactName: 'electron',
artifactSuffix: 'symbols',
arch: 'x64',
});
各作業系統對應的 NPM 快取路徑分別為:
- Linux:
$XDG_CACHE_HOME
or~/.cache/electron/
- MacOS:
~/Library/Caches/electron/
- Windows:
%LOCALAPPDATA%/electron/Cache
or~/AppData/Local/electron/Cache/
注意:Linux x64
和 Linux arm64
對應的 electron 映象是不同的,
關於開發模式啟動不了的問題
開發模式可能啟動不了,其原因或許是 my-electron、node_modules
下的 electron 未執行安裝,缺少 Electron 源。
想要解決,只需執行以下指令:
node ./node_modules/electron/cli.js
等待 electron 映象拉取完成後,即可正常進入開始模式。
總結
以上就是在不聯網的情況下使用 electron-builder 打包全平臺桌面應用的記錄。
- ~
- 本文完,感謝閱讀!
~
學習有趣的知識,結識有趣的朋友,塑造有趣的靈魂!