初次学习使用Electron,在打包第一个入门应用时就出现了老大难的问题,npm run package命令在运行时会去下载github的资源(如nsis、winCodeSign等),但是这个速度可就太感人。慢就不说了,最后还赤果果的用一大串红字告诉我打包失败。
报错信息如下:

[0] npm run build:main exited with code 0
[1] npm run build:renderer exited with code 0
• electron-builder version=22.13.1 os=10.0.19043
• loaded configuration file=package.json ("build" field)
• writing effective config file=release\build\builder-effective-config.yaml
• installing production dependencies platform=win32 arch=x64 appDir=D:\Code\Electron\test\release\app
• packaging platform=win32 arch=x64 electron=16.0.5 appOutDir=release\build\win-unpacked
• building target=nsis file=release\build\ElectronReact Setup 4.5.0.exe archs=x64 oneClick=true perMachine=false
• downloading url=https://github.com/electron-userland/electron-builder-binaries/releases/download/nsis-3.0.4.2/nsis-3.0.4.2.7z size=1.4 MB parts=1
• retrying attempt=1
• retrying attempt=2
• retrying attempt=3
⨯ part download request failed with status code 401
github.com/develar/app-builder/pkg/download.(*Part).doRequest
/Volumes/data/Documents/app-builder/pkg/download/Part.go:126
github.com/develar/app-builder/pkg/download.(*Part).download
/Volumes/data/Documents/app-builder/pkg/download/Part.go:67
github.com/develar/app-builder/pkg/download.(*Downloader).DownloadResolved.func1.1
/Volumes/data/Documents/app-builder/pkg/download/downloader.go:155
github.com/develar/app-builder/pkg/util.MapAsyncConcurrency.func2
/Volumes/data/Documents/app-builder/pkg/util/async.go:68
runtime.goexit
/usr/local/Cellar/go/1.16.5/libexec/src/runtime/asm_amd64.s:1371
⨯ D:\Code\Electron\test\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE failedTask=build stackTrace=Error: D:\Code\Electron\test\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE

问题就出在下载github资源太慢了,而cnpm是提供了对应的镜像源的,所以解决办法也挺简单,设置ELECTRON_BUILDER_BINARIES_MIRROR镜像源地址就行了,即修改 C:\Users\你的用户名\.npmrc 文件(如果没有该文件就直接创建),加入如下代码:

registry=https://registry.npm.taobao.org/
electron_mirror=https://npm.taobao.org/mirrors/electron/
isturl=https://npm.taobao.org/mirrors/node
ELECTRON_BUILDER_BINARIES_MIRROR=http://npm.taobao.org/mirrors/electron-builder-binaries/
ELECTRON_MIRROR=https://npm.taobao.org/mirrors/electron/

注:ELECTRON_BUILDER_BINARIES_MIRROR的地址可以改成https的试试。

然后再去运行npm run package,发现download部分很快就过去了,程序包也打好了,喜极而泣。