用 electron-builder 打包成 Windows exe

摘要:
加上 electron-builder 設定,`npm run dist` 產出 NSIS 安裝檔與免安裝版,並修正打包後才會出現的路徑問題。

根本原因:
原本三處路徑都假設程式是攤在資料夾裡跑的,打包成 asar 後會壞:
1. hook 腳本路徑會落在 app.asar 內,而 Claude Code 是用 `node <路徑>` 執行它,node 讀不到 asar 裡的檔案,hook 會直接失敗。
2. pets 資料夾同樣在 asar 內,使用者無法自己丟寵物進去,選單「開啟寵物資料夾」也開不起來。
3. 開機自動啟動寫入的是 `electron.exe + 專案路徑`,打包後沒有 node_modules,登錄值會指向不存在的檔案。

影響:
沒有可散佈的執行檔;直接打包的話 hook、換寵物、開機啟動三個功能都會壞掉。

修法:
- 新增 lib/paths.js:unpacked() 把 app.asar 換成 app.asar.unpacked,isPackaged() 以 process.defaultApp 判斷是否為打包版。
- build.asarUnpack 把 hook/ 與 pets/ 解到 asar 外,hooks-installer 與 main.js 的 PETS_DIR 都改走 unpacked()。
- autostart 打包後改用 process.execPath,並跳過開發版才需要的 electron.exe 存在檢查。
- NSIS 設為 per-user、可改安裝路徑、建立桌面與開始選單捷徑,解除安裝不刪 ~/.claude-pet。
- 新增 build/icon.ico(16–256,七種尺寸),取自小念 spritesheet 第 0 列第 6 欄的頭肩方形裁切。
- dist/ 加入 .gitignore;README 補上「打包成 exe」一節與安裝檔的使用方式。

驗證:
以 ELECTRON_RUN_AS_NODE 執行打包後的 exe(不開視窗)載入打包內的 lib,確認 isPackaged 為 true、hook 路徑指到 app.asar.unpacked 且檔案存在、autostart 指到 exe 本身、pets 掃得到 xiao-nian、renderer 讀得到 asar 內的 index.html;另確認 exe 版本資訊與七種尺寸圖示皆已嵌入。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-21 11:03:11 +08:00
co-authored by Claude Fable 5
parent a014f9a279
commit 56fd8448ba
9 changed files with 3545 additions and 10 deletions
+49 -2
View File
@@ -10,9 +10,56 @@
"hooks:uninstall": "node scripts/uninstall-hooks.js",
"autostart:install": "node scripts/autostart.js install",
"autostart:uninstall": "node scripts/autostart.js uninstall",
"autostart:status": "node scripts/autostart.js status"
"autostart:status": "node scripts/autostart.js status",
"dist": "electron-builder --win",
"pack": "electron-builder --win --dir"
},
"devDependencies": {
"electron": "^43.4.1"
"electron": "^43.4.1",
"electron-builder": "^26.0.12"
},
"author": "JianMiau",
"build": {
"appId": "com.jianmiau.claude-pet",
"productName": "Claude Pet",
"copyright": "JianMiau",
"directories": {
"output": "dist",
"buildResources": "build"
},
"files": [
"main.js",
"preload.js",
"renderer/**/*",
"lib/**/*",
"hook/**/*",
"pets/**/*",
"package.json"
],
"asarUnpack": [
"hook/**/*",
"pets/**/*"
],
"win": {
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
}
],
"icon": "build/icon.ico",
"artifactName": "${productName}-${version}-setup.${ext}"
},
"nsis": {
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
"createDesktopShortcut": true,
"createStartMenuShortcut": true,
"shortcutName": "Claude Pet",
"deleteAppDataOnUninstall": false
}
}
}