Yarn

Yarn is a fast, reliable, and secure package manager for JavaScript. Created by Facebook (Meta), it's an alternative to NPM with improved performance and additional features.

Installation

bash
# Install via NPM
npm install -g yarn

# Check version
yarn --version

Common Commands

bash
# Initialize project
yarn init

# Install dependencies
yarn install
# or simply
yarn

# Add dependency
yarn add react

# Add dev dependency
yarn add --dev eslint

# Remove dependency
yarn remove lodash

# Upgrade dependency
yarn upgrade react

# Run script
yarn build
yarn dev

Key Features

Fast Installation Parallel installation and caching make Yarn faster than NPM.

Offline Mode Install packages from cache without internet connection.

Deterministic Lockfile ensures consistent installs across machines.

Workspaces Manage multiple packages in a monorepo.

Lockfile

yaml
# yarn.lock
react@^18.2.0:
  version "18.2.0"
  resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz"
  integrity sha512-...
  dependencies:
    loose-envify "^1.1.0"

Yarn Workspaces

json
// package.json
{
  "private": true,
  "workspaces": [
    "packages/*"
  ]
}

Yarn vs NPM

Yarn

  • Faster parallel installation
  • Offline cache
  • Workspaces built-in
  • yarn.lock lockfile

NPM

  • Comes with Node.js
  • Larger ecosystem
  • package-lock.json lockfile
  • Improved significantly in recent versions

Yarn 2+ (Berry)

bash
# Enable Yarn 2+
yarn set version berry

# Install dependencies (Plug'n'Play)
yarn install

# Zero-installs with committed cache
yarn install --immutable

Learn More