An Introduction to Yarn: A Powerful JavaScript Package Manager
tags: [“JavaScript Package Manager”, “Yarn”, “npm”, “Facebook”, “Open Source”]
Yarn is a JavaScript Package Manager developed by Facebook. It is a direct competitor of npm, one of the most widely used package managers in the JavaScript ecosystem. Yarn is compatible with npm packages and serves as a drop-in replacement for npm. While it used to be faster than npm due to parallel download and caching, npm has caught up with many of its features. Regardless, Yarn remains a popular and powerful choice for managing JavaScript dependencies.
Installation
To install Yarn, it is not recommended to use npm. Instead, you can use system-specific installation methods listed on the Yarn website, such as Homebrew for macOS. After installation, you will have the yarn
command available in your shell.
Managing Packages
Yarn manages dependencies by writing them to a package.json
file in the root folder of your project. Dependencies are stored in the node_modules
folder, similar to npm.
Initializing a New Project
To initialize a new project with Yarn, you can use the yarn init
command. It will start an interactive prompt to help you quickly set up your project.
Installing Dependencies
If you already have a package.json
file with a list of dependencies, you can run yarn
or yarn install
to install the packages.
Installing Packages
To install a package locally, you can use the yarn add package-name
command. If you want to install a package globally, you can use yarn global add package-name
. Additionally, you can install a package locally as a development dependency using yarn add --dev package-name
.
Removing Packages
To remove a package, you can use the yarn remove package-name
command.
Inspecting Licenses
Yarn provides tools to inspect licenses of the dependencies in your project. The yarn licenses ls
command prints the license information of each dependency. Additionally, you can generate a disclaimer that includes all the licenses used by the projects in your project using yarn licenses generate-disclaimer
.
Inspecting Dependencies
To understand why a specific package was installed as a dependency, you can use the yarn why package-name
command. It provides information about the dependency tree and the reasons for installing a package.
Upgrading Packages
To upgrade a single package, you can use the yarn upgrade package-name
command. If you want to upgrade all packages, you can use yarn upgrade
. However, blindly upgrading all dependencies can sometimes lead to problems. Yarn provides an interactive upgrade tool, yarn upgrade-interactive
, which allows you to selectively update packages.
Upgrading Yarn
Currently, there is no auto-update command for Yarn. If you installed Yarn using Homebrew, you can use brew upgrade yarn
to upgrade it. If you installed Yarn using npm, you can use npm uninstall yarn -g
followed by npm install yarn -g
.