devStandard/docs/learning/4-nodejs/3-npm yarn pnpm.md
2025-03-29 14:35:49 +08:00

90 lines
2.9 KiB
Markdown
Executable File

# 3-npm yarn pnpm
https://yarn.bootcss.com/
## CLI 命令比较
| 作用 | npm | yarn | pnpm |
| --------- | ----------------------- | -------------------- | ---------------- |
| 安装 | npm install | yarn install | pnpm install |
| 安装的简写 | npm i | yarn add | pnpm add |
| 强制安装 | npm i xxx --force | yarn add xxx --force | pnpm add --force |
| 卸载 | npm unintall | yarn remove | pnpm remove |
| 卸载简写 | npm rm | yarn rm | pnpm rm |
| 全局安装 | npm i xxx --global/-g | yarn global add xxx | pnpm add -g xxx |
| 安装包(生产模式) | npm i xxx --save/-S | yarn add xxx | pnpm add xxx |
| 开发模式安装包 | npm i xxx --save-dev/-D | yarn add xxx -dev/-D | pnpm add -D xxx |
| 检查更新 | npm outdated | yarn outdated | pnpm outdated |
| 更新 | npm update | yarn upgrade | pnpm update |
| 全局更新 | npm update -g | yarn global upgrade | pnpm update -g |
| 运行 | npm run xxx | yarn run xxx | pnpm run xxx |
| 清除缓存 | npm cache clean | yarn cache clean | pnpm store path |
| 动态包执行 | npx xxx | yarn dlx xxx | pnpm dlx xxx |
| 查看全局安装的包 | npm list -g --depth 0 | yarn global list | pnpm list -g |
## 切换镜像源
```sh
npm install -g nnrm
nnrm ls
nnrm use xxx
```
## pnpm 删除缓存
```bash
# 每块硬盘每个分区上都有缓存
# 例如D盘的项目会在D盘建立缓存
# 删除不被硬链接的包
pnpm store prune
# 强制删除所有pnpm缓存
pnpm store path
rm -rf ~/.pnpm-store
```
## macos npm install -g 权限问题
```bash
# permission denied
使用n/nvm等管理器重新安装node, 且提前设置好安装的路径, 安装在不需要权限的路径, 例如 $HOME/.n/ 下
```
## 快速清理电脑上的 node_modules
```sh
npm i -g npkill
// 进入对应目录
npkill
```
## 配置文件指定镜像源
```sh
# 项目根目录
vim .npmrc
# 淘宝源
registry=https://registry.npmmirror.com/
```
## lock文件
```json
"vue": "3.0.11" 只装这个版本, 精确到补丁版本号
"vue": "~3.0.11" 可以装 3.0.* 的最新版本
"vue": "^3.0.11" 可以装 3.* 的最新版本
```
## 减少依赖
```sh
pnpm dedupe
```
pnpm原本会分别安装B1和B2,dedupe命令执行后,会检测到这是同一个包,然后安装一个兼容B1和B2的B版本,A和C都依赖这个B版本。
这样可以减少重复安装,节省磁盘空间。
此外,dedupe还可以删除不再被使用的依赖,进一步优化依赖树。
所以pnpm dedupe是一个很有用的命令,可以有效优化pnpm安装的模块大小,减少不必要的重复依赖。