废宅阿斗 NPM 即将被 Node.js 官方抛弃 → Corepack
## 楔子
突然发现在 Node.js 16.9.0 的官方文档里面,多了个 Experimental 的 Corepack :
Corepack is an experimental tool to help with managing versions of your package managers. It exposes binary proxies for each supported package manager that, when called, will identify whatever package manager is configured for the current project, transparently install it if needed, and finally run it without requiring explicit user interactions.
看完一脸懵逼:这是啥?要干掉 NPM?为啥这么突然?
于是进一步翻了仓库和对应的讨论:
Corepack is a zero-runtime-dependency Node script that acts as a bridge between Node projects and the package managers they are intended to be used with during development. In practical terms, Corepack will let you use Yarn and pnpm without having to install them - just like what currently happens with npm, which is shipped by Node by default.
摘自: https:// github.com/nodejs/corep ack/blob/main/DESIGN.md
简单来说,Corepack 会成为 Node.js 官方的内置 CLI,用来管理『包管理工具(npm、yarn、pnpm、cnpm)』,用户无需手动安装,即『包管理器的管理器』。
## 初体验
先安装 Node.16.9.0 版本,然后在
package.json
中声明对应的包管理工具:
// package.json
"name": "corepack-test",
"packageManager": "yarn@2.0.0"
玩起来:
# 单应用激活
$ corepack enable
# 用声明的包管理器,会自动下载对应的 yarn,然后再执行
$ yarn install
# 用非声明的包管理器,会自动拦截报错
$ pnpm install
Usage Error: This project is configured to use yarn
我嚓,没全局安装 yarn 也能找到命令,怎么搞的?分析了下,非常粗暴。。。
$ which corepack
/Users/tz/.nvs/node/16.9.0/x64/bin/corepack
$ ll /Users/tz/.nvs/node/16.9.0/x64/bin/
corepack -> ../lib/node_modules/corepack/dist/corepack.js
npm -> ../lib/node_modules/npm/bin/npm-cli.js
npx -> ../lib/node_modules/npm/bin/npx-cli.js
pnpm -> ../lib/node_modules/corepack/dist/pnpm.js
pnpx -> ../lib/node_modules/corepack/dist/pnpx.js