Using other package managers with node has become a whole lot easier

Introducing corepack

Using other package managers with node has become a whole lot easier

If you still are not aware, node v16.9.0 and v14.19.0 was launched with corepack nodejs.org/api/corepack.html. A developer can use Corepack to define alternative package managers like yarn and pnpm. Node will then automatically get the required version of the package manger.

Corepack can also be installed as a global package on earlier node versions.

Benefits

Using package managers this way has two main benefits

  1. Easily synchronize package manager and their versions amongst developers. Though yarn 2+ solves this issue in its own way.
  2. No install step required for the package managers.

Enable

It's much easier to understand with an example.

On a machine with node installed

corepack enable

and that is it!. Now the required package manger will be available when executed.

If corepack is not found in your system, then you can install it as a global package

npm i -g corepack

Use

For example, now to create a new project with yarn, in a folder just execute

yarn init -2

Similarly you are free to use pnpm pnpm.io as well.

Update package.json

A new field in package.json has been introduced to fix a project to a particular package manager version.

{
  name: 'yarn-test',
  packageManager: 'yarn@3.2.0'
}

This ensures that every developer in your team will use the same version of the package manager.

In case a developer tries to any other package manager, they will get an error

image.png

Running the same version

The major work is all done!

Just run your package manager inside your repo and it should run the version defined in your package.json

For example if the package.json had

{
    ...
    "packageManager": "pnpm@6.32.2"
}

Running pnpm in this project will use the same version.

pnpm -v
6.32.2

Updating the global version

If you wish to update the package manger version outside of any projects, run

corepack prepare pnpm@6.32.2 --activate

This will update the global pnpm version to 6.32.2.

Conclusions

I wish I had more to say, but corepack makes switching to other package managers a breeze. What qualities distinguish your preferred package manager?