Yarn Installation and Configuration Guide

Yarn is a popular JavaScript package management tool designed to improve the speed and reliability of dependency management. This article will provide detailed instructions on how to install Yarn on different operating systems and configure its common options.

1. Installing Yarn

If Node.js and npm are already installed on your system, you can install Yarn using the following command:

Terminal window
1
npm install --global yarn

Install with Homebrew (macOS)

On macOS, you can use Homebrew to install Yarn:

Terminal window
1
brew install yarn

Install with Official Script (Linux)

For Linux users, you can use the official installation script:

Terminal window
1
curl -o- -L https://yarnpkg.com/install.sh | bash

2. Verify Installation

After installation, you can check the Yarn version to confirm if the installation was successful:

Terminal window
1
yarn --version

3. Configuring Yarn

Configure Registry

Yarn uses the default npm registry, but you can set other registry sources to improve speed, such as using the Taobao mirror:

Terminal window
1
yarn config set registry https://registry.npm.taobao.org

Configure Cache Directory

You can change Yarn’s cache directory:

Terminal window
1
yarn config set cache-folder /path/to/cache

Configure Global Package Directory

If you want to install global packages to a custom directory, you can set the prefix configuration:

Terminal window
1
yarn config set prefix /path/to/global/node_modules

Use .yarnrc File

You can also configure Yarn by creating or editing the .yarnrc file in the root directory of your project:

Terminal window
1
registry "https://registry.npmjs.org/"
2
cache-folder "/path/to/cache"

4. Using Yarn

Initialize a Project

Initialize a new Yarn project in your project directory:

Terminal window
1
yarn init

Install Dependencies

Install project dependencies:

Terminal window
1
yarn add <package-name>

Install development dependencies:

Terminal window
1
yarn add <package-name> --dev

Update Dependencies

Update all dependencies in the project:

Terminal window
1
yarn upgrade

Remove Dependencies

Remove dependencies that are no longer needed:

Terminal window
1
yarn remove <package-name>