Files

83 lines
2.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Electron 项目开发环境完整配置指南
以下涵盖从 Node 版本管理、镜像源配置到 electron-builder 打包的全流程。
## 一、Node 版本管理(nvm
安装 nvm-windows 后,使用以下命令管理 Node 版本:
```bash
# 安装需要的版本(以 Node 18 为例)
nvm install 18
# 设为当前终端使用的版本
nvm use 18
# 设为默认版本(新终端自动生效)
nvm alias default 18
```
## 二、配置镜像源
npm v9+ 已不支持 `npm config set` 设置自定义键名,必须直接编辑 `.npmrc` 文件。
### 推荐方式:项目级 .npmrc(仅对当前项目生效)
在项目根目录下创建或编辑 `.npmrc` 文件,写入以下内容:
```
registry=https://registry.npmmirror.com
ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/
ELECTRON_BUILDER_BINARIES_MIRROR=https://npmmirror.com/mirrors/electron-builder-binaries/
```
如果想让所有项目都生效,编辑全局 `.npmrc`(可通过 `npm config get userconfig` 查看路径),内容同上。
## 三、配置文件说明
| 配置项 | 作用 |
|:-------|:-----|
| `registry` | npm 包下载源,避免从 npmjs.org 拉包缓慢 |
| `ELECTRON_MIRROR` | Electron 二进制文件(electron.exe 等)的下载源 |
| `ELECTRON_BUILDER_BINARIES_MIRROR` | electron-builder 打包工具链的下载源 |
## 四、开始打包
> **关键:** 保存 `.npmrc` 后务必新开一个命令行窗口,否则环境变量不生效。
```bash
# 1. 清除旧缓存,确保不走之前的错误源
npm cache clean --force
# 2. 安装依赖(如果还没装或 node_modules 不完整)
npm install
# 3. 执行构建
npm run build
```
构建成功后,安装包会生成在 `dist/` 目录下。
## 五、一次性完整操作步骤总结
```bash
# ① 确保 Node 版本正确
nvm use 18
# ② 在项目根目录创建 .npmrc,写入:
# registry=https://registry.npmmirror.com
# ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/
# ELECTRON_BUILDER_BINARIES_MIRROR=https://npmmirror.com/mirrors/electron-builder-binaries/
# ③ 关闭当前终端,新开一个终端,然后执行:
npm cache clean --force
npm install
npm run build
```
## 六、常见问题排查
- **`ELECTRON_MIRROR is not a valid npm option`**npm 版本太新,禁止用 `npm config set` 设置自定义键,改用编辑 `.npmrc` 文件解决。
- **下载 Electron 还是走 GitHub**:检查 `.npmrc` 文件名是否正确(不要写成 `.npmrc.txt`),以及是否重新打开了终端。
- **nvm 切换版本后 node 没变**:确保以管理员身份运行终端,且 nvm 安装路径没有中文或空格。