91 lines
2.8 KiB
Markdown
91 lines
2.8 KiB
Markdown
# Electron 项目开发环境完整配置指南
|
||
|
||
以下涵盖从 Node 版本管理、镜像源配置到 electron-builder 打包的全流程,基于你当前 `C:\Workspace\MarkLite` 项目的实际情况。
|
||
|
||
## 一、Node 版本管理(nvm)
|
||
|
||
安装 nvm-windows 后,使用以下命令管理 Node 版本:
|
||
|
||
```bash
|
||
# 安装需要的版本(以 Node 18 为例)
|
||
nvm install 18
|
||
|
||
# 设为当前终端使用的版本
|
||
nvm use 18
|
||
|
||
# 设为默认版本(新终端自动生效)
|
||
nvm alias default 18
|
||
```
|
||
|
||
## 二、配置镜像源
|
||
|
||
你的 npm 版本是 v11.12.1,已经不支持 `npm config set ELECTRON_MIRROR` 这种自定义键名的方式,必须直接编辑 `.npmrc` 文件。
|
||
|
||
### 推荐方式:项目级 .npmrc(仅对当前项目生效)
|
||
|
||
在项目根目录 `C:\Workspace\MarkLite>` 执行:
|
||
|
||
```bash
|
||
notepad .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`,路径位于 `C:\Users\Administrator.USER-20250226EX\.npmrc`,内容同上。
|
||
|
||
## 三、配置文件说明
|
||
|
||
| 配置项 | 作用 |
|
||
|:-------|:-----|
|
||
| `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
|
||
notepad C:\Workspace\MarkLite\.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 安装路径没有中文或空格。
|