Electron 安装
Node 环境准备、npm 安装 Electron、镜像加速、验证安装。
前置条件
node -v
npm -vv22.22.2
10.9.7Electron needs Node to run npm and the packaging tools, but the app runtime does not use the system Node — it ships its own. End users never install Node.
装到项目里
mkdir my-app && cd my-app
npm init -y
npm install --save-dev electronadded 78 packages in 12sUse --save-dev, not --save: Electron is needed only for development and packaging. Some packagers copy dependencies into the bundle, adding tens of MB.
国内镜像加速
# 临时
ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ npm install --save-dev electron
# 永久(写进 ~/.npmrc)
electron_mirror=https://npmmirror.com/mirrors/electron/npm install electron additionally fetches a tens-of-MB prebuilt binary from GitHub, which often times out in China. The mirror only affects that download, not the npm package itself.
验证
npx electron --versionv33.0.0npx uses the project-local copy instead of a global one. A global install tends to drift from the project version — not recommended.
常见安装问题
| Symptom | Cause |
|---|---|
| Download failed | GitHub 不可达,需要配镜像 |
| EACCES / permission | 用了 sudo npm i -g,或目录权限不对 |
| Version mismatch | 全局与项目各装了一份 |
| Cannot find module | main 字段指向的文件不存在 |
| App won't start on Linux | 缺 libnss3、libgbm 等系统库 |
"main" field must point at a real file. When it does not, Electron reports Unable to find Electron app without mentioning main — a long detour for a one-character typo.前置条件
node -v
npm -vv22.22.2
10.9.7Electron 依赖 Node 运行 npm 与打包工具,但应用运行时不用系统的 Node——它自带一份。所以用户机器上不需要装 Node。
装到项目里
mkdir my-app && cd my-app
npm init -y
npm install --save-dev electronadded 78 packages in 12s用 --save-dev 而不是 --save:Electron 只在开发和打包时需要,不该进 dependencies。有些打包工具会把 dependencies 一起塞进产物,多出几十 MB。
国内镜像加速
# 临时
ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ npm install --save-dev electron
# 永久(写进 ~/.npmrc)
electron_mirror=https://npmmirror.com/mirrors/electron/npm install electron 会额外去 GitHub 下载几十 MB 的预编译包,国内经常卡在这一步直到超时。配镜像只影响这个二进制下载,不影响 npm 包本身。
验证
npx electron --versionv33.0.0npx 会用项目里装的那份,而不是全局的。全局装 Electron(npm i -g electron)容易和项目版本冲突,不推荐。
常见安装问题
| 现象 | 原因 |
|---|---|
| 下载失败 | GitHub 不可达,需要配镜像 |
| 权限错误 | 用了 sudo npm i -g,或目录权限不对 |
| 版本不一致 | 全局与项目各装了一份 |
| 找不到模块 | main 字段指向的文件不存在 |
| Linux 起不来 | 缺 libnss3、libgbm 等系统库 |
package.json 里 "main" 必须指向真实存在的文件。写错时 Electron 会报 Unable to find Electron app,错误信息不提 main 字段,很容易查半天。