Yarn's release marked a major step forward for package management in node.js, delivering features we now take for granted such as deterministic sub-dependency resolution and an offline cache. While these days the feature gulf between Yarn and NPM isn't so large, there are several things that it does still do better than NPM, particularly after the release of Yarn 2.

Today we're not here to advocate for the choice of one package manager over another. It mostly just depends on your personal requirements and preferences. That said, if you are somebody who wants to give Yarn a try, this guide will show you how to install and use Yarn using NPM.

Prerequisites

It probably goes without saying, but you should install Node before installing Yarn. This will give you access to the NPM so that you can easily install Yarn, and well, give your package manager something to manage.

If you're unsure whether you have node.js installed, you can follow this guide to check your node.js version or just run node -v. If it isn't present, use:

curl -fsSL https://deb.nodesource.com/setup_19.x | sudo -E bash - &&\
sudo apt-get install -y nodejs

Check the GitHub to ensure this command is up to date and correct for your distribution.

Installing Yarn with Corepack

Node.js versions 16.10 and greater ship with a binary called Corepack. Corepack lets you use Yarn without globally installing it, but is not enabled by default. To enable it, you need to run:

corepack enable

You can now navigate to your chosen directory and start a new project with:

yarn init -2

You'll see that it creates package.json, yarn.lock, and readme.md in your directory. Now you can make sure you have all of the dependencies with:

yarn
yarn install

Finally, add the packages you want. For example:

yarn add lodash