Last updated on

Corepack 安利

简介

https://github.com/nodejs/corepack

Zero-runtime-dependency package acting as bridge between Node projects and their package managers

包管理器的管理器

In practical terms, Corepack lets you use Yarn, npm, and pnpm without having to install them.

Corepack is distributed by default with all recent Node.js versions. 我这边看新的 14、16 都是有的

使用方式

  1. 启用 corepack enable
  2. 加 packageManager 在项目的 package.json 文件中加
{
  "packageManager": "yarn@3.2.3+sha224.953c8233f7a92884eee2de69a1b92d1f2ec1655e66d08071ba9a02fa"
}

Here, yarn is the name of the package manager, specified at version 3.2.3, along with the SHA-224 hash of this version for validation. packageManager@x.y.z is required. The hash is optional but strongly recommended as a security practice. Permitted values for the package manager are yarn, npm, and pnpm.

packageManager@x.y.z 是必须的,后面的 hash 是可选的

使用效果

新建个项目

{
  "name": "corepack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

在 package.json 所在路径执行pnpm --version

 pnpm --version
8.6.11

添加 "packageManager": "pnpm@7.1.1",

{
  "name": "corepack",
  "version": "1.0.0",
  "description": "",
  "packageManager": "pnpm@7.1.1",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
workspace/repositories/corepack is 📦 v1.0.0 via v16.20.0
 pnpm --version
7.1.1

注意到我这里已经自动换成了项目规定的 packageManager

如果尝试使用 yarn 呢?

 yarn
Usage Error: This project is configured to use pnpm

$ yarn ...

但是 npm 还没拦,可以用