Installing and Using Yarn on Ubuntu

Yarn is a powerful JavaScript package manager that is compatible with npm and helps automate the process of installing, updating, configuring, and removing npm packages. Yarn provides speed and reliability by caching downloaded packages and parallelizing operations. In this tutorial, we will cover how to install both the latest version and classic version of Yarn on Ubuntu, along with an overview of basic Yarn commands and options.
Installing the Latest Yarn Version
To install and manage the latest Yarn version, we recommend using Corepack, a binary included in newer Node.js releases that serves as a point of contact between the user and Yarn. Here are the steps to install Yarn using Corepack:
-
Ensure your Node.js version is up-to-date. Check the version with the command:
node -v
Corepack requires Node.js 16.10 or later. If the output shows an older version, update Node.js. -
Start Corepack by typing:
corepack enable
Note: If Corepack does not exist on your system, install it by typing:sudo npm install -g corepack
-
Install the latest version of Yarn with the command below:
corepack prepare yarn@stable --activate
-
Type the following command to test the installation and check the Yarn version:
yarn --version
To update the binary to the latest version, run:yarn set version stable
Installing Classic Yarn Version
Although the classic versions of Yarn before 2.0 are in maintenance mode, you can still install Yarn 1.x using the official Yarn repositories and npm. Here's how:
Option 1: Install Yarn Classic Via Repository
-
Add the GPG key:
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/yarn.gpg
The GPG key ensures that you are installing authentic software. -
Add the Yarn repository:
echo "deb [signed-by=/etc/apt/trusted.gpg.d/yarn.gpg] https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
-
Update your local repository listings:
sudo apt update
-
Install Yarn:
sudo apt install yarn
This command installs Yarn and, if you don’t already have Node.js installed, your package manager will install it for you.
Option 2: Install Yarn Classic Using NPM
-
Check if npm is installed:
npm --version
If you don’t have npm, install it by runningsudo apt install npm
. -
To install Yarn with npm, enter:
sudo npm install -g yarn
Source: Linux Journal - The Original Magazine of the Linux Community