Lesson 10-Yarn Basic Concepts and Usage

Introduction to Yarn

Historical Background

Yarn, a package manager, was first released by Facebook in March 2016. It was created to address performance and reliability issues encountered by npm (Node Package Manager) in large-scale projects and organizations. As the JavaScript ecosystem grew rapidly, npm became one of the most popular package managers, but its installation speed and consistency became bottlenecks in large projects or slow network environments.

Differences from npm

Yarn and npm share many functional similarities as tools for managing JavaScript project dependencies, but Yarn introduces several key improvements:

  1. Parallel Installation: Yarn supports parallel dependency installation, allowing multiple packages to be installed simultaneously, significantly speeding up the process.
  2. Deterministic Installation: Yarn uses a yarn.lock file to ensure consistent dependency installations across environments, addressing npm’s inconsistency issues due to version differences.
  3. Offline Mode: Yarn caches installed packages, enabling fast installations from local cache even in unstable network conditions.
  4. Faster Recovery: Yarn recovers faster than npm by skipping already-installed packages and only installing those not yet present.
  5. Better User Experience: Yarn offers detailed command-line output and additional commands like yarn why and yarn outdated, helping developers better understand and manage dependencies.

Core Features and Advantages

  1. Performance: Parallel installation and caching mechanisms drastically improve installation speed, especially in large projects.
  2. Consistency: The yarn.lock file ensures identical dependency installations across all developers and environments, avoiding version conflicts.
  3. Offline Mode: Yarn can install dependencies from local cache without an internet connection.
  4. Predictability: Yarn’s installation process is predictable, reducing differences between development and production environments.
  5. Ease of Use: Yarn’s command-line interface is intuitive, offering rich commands and options for efficient project management.
  6. Compatibility: Yarn is compatible with npm’s package.json files, allowing seamless migration from npm projects.

Installation and Configuration

Installing Yarn

1. Install via npm

The simplest way to install Yarn is through npm. Ensure Node.js and npm are installed, then run:

npm install -g yarn

This installs Yarn globally. Verify the installation with:

yarn --version

2. Alternative Installation Methods

If npm is unavailable or unsuitable, Yarn can be installed via:

  • Direct Binary Download: Download binaries for your operating system from Yarn’s GitHub repository or official website and install manually.
  • Package Managers: On Linux, use APT, YUM, or other package managers to install Yarn.
  • Docker Containers: In Docker environments, add RUN npm install -g yarn to the Dockerfile.

Configuring Yarn

1. Configure Global Path

By default, Yarn installs global packages in /usr/local/lib/node_modules (on macOS and Linux). To customize this location, edit or create the .yarnrc file in your home directory:

globalFolder: "/path/to/your/custom/global/folder"

2. Configure Cache Directory

Yarn caches packages in /Users/<username>/.yarn by default (on macOS and Linux). To change this, update .yarnrc:

cacheFolder: "/path/to/your/custom/cache/folder"

3. Configure Registry Mirror

For slow npm registry access, configure Yarn to use a mirror, such as Taobao’s npm mirror:

yarn config set registry https://registry.npm.taobao.org

4. Configure Private Registry

To use a private registry (e.g., http://my.private.registry/), configure:

yarn config set registry http://my.private.registry/

For authenticated registries, set credentials:

yarn config set username <your-username>
yarn config set password <your-password>

5. Configure Parallel Installation

Yarn installs dependencies in parallel by default, but you can adjust concurrency, e.g., set maximum parallel installations to 4:

yarn config set concurrent 4

Using Yarn

1. Initialize a Project

Create a package.json file:

yarn init

2. Add Dependencies

Add a dependency:

yarn add <package-name>

3. List Dependencies

View all project dependencies:

yarn list

4. Upgrade Dependencies

Upgrade a dependency to the latest version:

yarn upgrade <package-name>

5. Remove Dependencies

Remove a dependency:

yarn remove <package-name>

Advanced Configuration

Yarn supports advanced options, including:

  • Workspaces: Manage multi-project repositories.
  • Plugins: Extend Yarn’s functionality.
  • Hooks: Run custom scripts before or after Yarn operations.

Edit yarnrc.yml in the project root for detailed configurations.

Basic Commands

Initialize a Project

yarn init

Initializes a new project, creating a package.json file. Typically used at project start.

yarn init

Add Dependencies

yarn add

Adds dependencies to the project, specifying versions or ranges if needed. Defaults to the latest stable version.

yarn add <package-name> # Latest stable version
yarn add <package-name>@<version> # Specific version
yarn add <package-name>@latest # Latest version
yarn add <package-name>@next # Next version

Remove Dependencies

yarn remove

Removes unneeded dependencies.

yarn remove <package-name>

Upgrade Dependencies

yarn upgrade

Upgrades dependencies to the latest or specified version.

yarn upgrade <package-name> # Latest version
yarn upgrade <package-name>@<version> # Specific version

Downgrade Dependencies

yarn downgrade

Downgrades dependencies to a specified version.

yarn downgrade <package-name>@<version>

List Dependencies

yarn list

Displays all project dependencies with version information.

yarn list

Check Dependencies

yarn check

Verifies that installed dependencies match the yarn.lock file.

yarn check

Clear Cache

yarn cache clean

Clears Yarn’s cache, useful for resolving installation issues or forcing redownloads.

yarn cache clean

View Package Information

yarn info

Retrieves details about a package, including version history, author, and license.

yarn info <package-name>

Run Scripts

yarn <script-name>

Executes scripts defined in package.json.

yarn start # Runs the `start` script if defined

List Outdated Dependencies

yarn outdated

Lists dependencies with available updates.

yarn outdated

Deduplicate Dependencies

yarn dedupe

Optimizes the dependency tree by reducing duplicates.

yarn dedupe

Trace Dependency Sources

yarn why

Identifies why a dependency was installed, tracing its origin.

yarn why <package-name>

Generate Lockfile

yarn install

Generates or updates the yarn.lock file, ensuring dependency consistency.

yarn install

Locate Executable Scripts

yarn bin

Displays the path to executable scripts, useful for globally installed packages.

yarn bin

Check Version

yarn --version

Shows the current Yarn version.

yarn --version

Access Help

yarn help

Displays help documentation for all available commands.

yarn help

Use Cases

  • Project Initialization: Use yarn init to create package.json.
  • Dependency Management: Use yarn add, yarn upgrade, yarn remove, and yarn dedupe.
  • Script Execution: Run project scripts with yarn <script-name>.
  • Version Control: Ensure dependency consistency with yarn check.
  • Troubleshooting: Use yarn why and yarn outdated to diagnose dependency issues.

Daily Usage

Installing Project Dependencies

Before starting a project, ensure Yarn is installed. Below is a detailed guide to installing project dependencies with Yarn.

Initialize a Project

Run yarn init to create a package.json file containing project metadata and dependency information:

yarn init

Add Dependencies

Use yarn add to include required dependencies. For example, to add the Express framework:

yarn add express

This adds Express to package.json, installs it in node_modules, and updates or generates yarn.lock for consistency.

Running Scripts

Yarn serves as both a package manager and a tool for running project scripts defined in package.json, such as starting a server, running tests, or building the project.

Define Scripts

In package.json, add or edit the "scripts" field to define scripts:

{
  "scripts": {
    "start": "node server.js",
    "test": "jest",
    "build": "webpack"
  }
}

This defines three scripts: start (server), test (tests), and build (project build).

Run Scripts

Execute scripts with Yarn. For example, to start the server:

yarn start

This runs the "start" script from package.json.

Creating and Publishing Packages

If you’re developing a library or tool, you may want to package and publish it to the npm registry for others to use.

Create a Package

Ensure your project includes essential metadata (name, version, author) in package.json.

Build the Package

Before publishing, run pre-build scripts to prepare the release, such as compiling code or generating documentation. Define these in package.json:

{
  "scripts": {
    "prepublishOnly": "npm run build"
  }
}

The "prepublishOnly" script runs automatically before publishing.

Log in to npm

Log in to your npm account using the npm CLI:

npm login

Follow prompts to enter your npm username, password, and email.

Publish the Package

Publish the package with:

npm publish

Note: Yarn does not directly support the publish command, but npm’s publish command is compatible, as Yarn and npm share the same publishing workflow.

Share your love