Electron 安装时报下载404【已解决】

3,815 阅读1分钟

问题

安装Electron时总有一个烦人的事情,如下:

$ npm i
npm WARN deprecated sourcemap-codec@1.4.8: Please use @jridgewell/sourcemap-codec instead
npm ERR! code 1
npm ERR! path D:\workspace\electron\live-stage\node_modules\electron
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node install.js
npm ERR! HTTPError: Response code 404 (Not Found) for https://github.com/electron/electron/releases/download/13.6.9/electron-v13.6.9-win32-x64.zip
npm ERR!     at EventEmitter.<anonymous> (D:\workspace\electron\live-stage\node_modules\got\source\as-stream.js:35:24)
npm ERR!     at EventEmitter.emit (node:events:513:28)
npm ERR!     at module.exports (D:\workspace\electron\live-stage\node_modules\got\source\get-response.js:22:10)
npm ERR!     at ClientRequest.handleResponse (D:\workspace\electron\live-stage\node_modules\got\source\request-as-event-emitter.js:155:5)
npm ERR!     at Object.onceWrapper (node:events:628:26)
npm ERR!     at ClientRequest.emit (node:events:525:35)
npm ERR!     at ClientRequest.origin.emit (D:\workspace\electron\live-stage\node_modules\@szmarczak\http-timer\source\index.js:37:11)
npm ERR!     at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:693:27)
npm ERR!     at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
npm ERR!     at TLSSocket.socketOnData (node:_http_client:534:22)

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Administrator\AppData\Local\npm-cache\_logs\2023-08-21T08_25_25_241Z-debug-0.log

解决

这个问题其实官网已经给了解决方案,有好几个方案。如果懒得看,这里直接推荐一个方案,在.npmrc里面加入下面两行即可,.npmrc应该放在项目根目录下,如果不有,新建即可。

ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/"
ELECTRON_CUSTOM_DIR="{{ version }}"

原因

在安装过程中,electron 模块会通过 electron-download 为您的平台下载 Electron 的预编译二进制文件。 这将通过访问 GitHub 的发布下载页面来完成 (https://github.com/electron/electron/releases/tag/v$VERSION, 这里的 $VERSION 是 Electron 的确切版本).

如果您无法访问GitHub,或者您需要提供自定义构建,则可以通过提供镜像或现有的缓存目录来实现。

镜像方式

您可以使用环境变量来覆盖基本 URL,查找 Electron 二进制文件的路径以及二进制文件名。 electron/get 使用的网址组成如下:

url = ELECTRON_MIRROR + ELECTRON_CUSTOM_DIR + '/' + ELECTRON_CUSTOM_FILENAME

例如,使用一个中国的镜像:

ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/"

默认情况下,ELECTRON_CUSTTOM_DIR被设置为 v$VERSION。 要更改格式,请使用 {{ version }} 占位符。 例如,version-{{ version }} 被解析为 version-5.0.0{{ version }} 被解析为 5.0.0, v{{ version }} 与默认值等价。 更具体的例子,使用中国镜像:

ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/"
ELECTRON_CUSTOM_DIR="{{ version }}"

上述配置将从类似于 https://npmmirror.com/mirrors/electron/8.0.0/electron-v8.0.0-linux-x64.zip 这样的网址下载。

如果您的镜像在官方 Electron 版本中提供不同校验和,你可能必须将 electron_use_remote_checksums=1 设置为 Electron 使用远程 SHASUMS256.txt 文件来验证校验和 而不是嵌入校验和。

Electron 安装指导