Windows10配置Node开发环境

下载 Node.js

Node.js 官网: https://nodejs.org/zh-cn/download/

使用nvm管理Node版本

nvm: https://github.com/nvm-sh/nvm

nvm-windows: https://github.com/coreybutler/nvm-windows

设置国内Node和npm镜像:

1
2
nvm npm_mirror https://npmmirror.com/mirrors/npm/
nvm node_mirror https://npmmirror.com/mirrors/node/

修改 npm 全局模块安装路径

全局模块默认安装路径: %USERPROFILE%\AppData\Roaming\npm

本例 Node.js 安装路位置: D:\Applications\nodejs

  1. 在 Nodejs 的根目录下创建全局模块路径node_global和全局缓存路径node_cache

  2. 设置全局模块路径和全局缓存路径(注意:路径中不能包含空格否则 npx 使用不了)

1
2
3
4
5
6
# 全局模块路径
npm config set prefix "D:\Applications\nodejs\node_global"
# 全局缓存路径
npm config set cache "D:\Applications\nodejs\node_cache"
# 查看配置
npm config list
  1. 将以下路径添加至环境变量
1
2
D:\Applications\nodejs
D:\Applications\nodejs\node_global

修改 npm 为国内镜像

在命令行依次输入以下命令

1
2
3
4
5
6
7
8
# 设置国内镜像
npm config set registry https://registry.npm.taobao.org
# 如果开发electron,则需要设置electron国内镜像
npm config set electron_mirror=https://npm.taobao.org/mirrors/electron/
# electron打包是也需要设置镜像,否则特别慢
npm config set electron-builder-binaries_mirror=https://npm.taobao.org/mirrors/electron-builder-binaries/
# 查看npm的仓库地址
npm config get registry

安装 yarn

在全局模块 yarn 根目录下创建全局模块路径yarn_global和缓存路径yarn_cache

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 全局安装
npm install -g yarn
# 查看版本号
yarn --version
# 设置国内镜像
yarn config set registry https://registry.npm.taobao.org
# 如果开发electron,则需要设置electron国内镜像
yarn config set electron_mirror=https://npm.taobao.org/mirrors/electron/
# electron打包是也需要设置镜像,否则特别慢
yarn config set electron-builder-binaries_mirror=https://npm.taobao.org/mirrors/electron-builder-binaries/
# 全局模块路径
yarn config set global-folder "D:\Applications\nodejs\node_global\node_modules\yarn\yarn_global"
# 设置缓存路径
yarn config set cache-folder "D:\Applications\nodejs\node_global\node_modules\yarn\yarn_cache"
# 查看配置
yarn config list

安装pnpm

1
2
3
4
5
6
# 全局安装
npm install -g pnpm
# 设置存储库
pnpm config set store-dir D:\Applications\nodejs\node_global\node_modules\pnpm\store-dir
pnpm config set state-dir D:\Applications\nodejs\node_global\node_modules\pnpm\state-dir
pnpm config set cache-dir D:\Applications\nodejs\node_global\node_modules\pnpm\cache-dir

https://pnpm.io/zh/next/npmrc#store-dir

https://pnpm.io/zh/next/npmrc#state-dir

https://pnpm.io/zh/next/npmrc#cache-dir

可能出现的报错

错误描述: yarn : 无法将“yarn”项识别为 cmdlet

1
2
3
4
5
6
yarn : 无法将“yarn”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确 ,然后再试一次。 所在位置 行:1 字符: 1

+ yarn --version
+ ~~~~
+ CategoryInfo : ObjectNotFound: (yarn:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

解决方案: 管理员身份运行 PowerShell

1
2
# 设置RemoteSigned
set-ExecutionPolicy RemoteSigned

错误描述: npm ERR! reason: certificate has expired

解决方案:

1
2
npm cache clean --force
npm config set strict-ssl false