Jesse A. Green / notebook

Yarn User Guide

Generated June 2026 from yarnpkg/yarn at c2dda50

AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it.

Yarn is a fast, reliable, and secure dependency manager for JavaScript and Node.js projects. It reads a package.json, resolves the full dependency graph, downloads packages into a global cache, and links them into your project's node_modules — recording the exact result in a yarn.lock file so that every install on every machine is identical.

This guide covers Yarn 1 ("Classic"), version 1.23.0-0. It documents every command and command-line flag exactly as implemented in the source, with copy-paste-runnable examples.

Note

Yarn ships two interchangeable executables: yarn and yarnpkg. Both point to the same program. Use yarnpkg on systems where the yarn name collides with another tool (for example, the Hadoop YARN resource manager). Every example below works with either name.

Important

This guide describes Yarn 1 (Classic). Yarn 1 introduced the concept of a modern, deterministic JavaScript package manager and remains widely used, but active feature development happens in Yarn 2+ ("Berry"). You can migrate an existing project to a newer line at any time with yarn set version berry or yarn init -2 (see Upgrading Yarn itself).


Table of Contents

  1. Quick Start
  2. Installation
  3. Core Concepts You Need to Know
  4. Everyday Usage
  5. Common Workflows
  6. Workspaces (Monorepos)
  7. Publishing Packages
  8. Global Packages
  9. Local Development with Links
  10. Security & Auditing
  11. Advanced Usage
  12. Global Flags Reference
  13. Configuration (.yarnrc)
  14. How Yarn Works
  15. Troubleshooting
  16. FAQ
  17. Command Reference

1. Quick Start

Get a project running in three commands.

# 1. Create a package.json interactively (or use -y for defaults)
yarn init -y

# 2. Add the dependencies you need
yarn add react react-dom

# 3. Install everything declared in package.json
yarn install

Expected output from yarn add react react-dom:

yarn add v1.23.0
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 4 new dependencies.
info Direct dependencies
├─ react@18.2.0
└─ react-dom@18.2.0
✨  Done in 2.31s.

Tip

In a project that already has a package.json and yarn.lock, you usually only need a single command — yarn (with no arguments) — to reproduce the exact dependency tree. This is the most common everyday operation.


2. Installation

Yarn is distributed through many channels. Pick the one that matches your platform. Yarn requires Node.js to run.

Important

Supported Node.js versions for Yarn 1.23 are ^4.8.0 || ^5.7.0 || ^6.2.2 || >=8.0.0. The package.json engines field declares a looser floor of >=4.0.0, but Yarn emits a warning at runtime if you run it on a Node version outside the supported set. Suppress that warning with --no-node-version-check if you know what you are doing.

npm

If you already have npm, this is the simplest route:

npm install --global yarn

macOS (Homebrew)

brew install yarn

Linux (Debian/Ubuntu)

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update && sudo apt-get install yarn

Linux (RPM / Fedora / CentOS)

sudo yum install yarn

Alpine Linux

apk add yarn

Windows (Chocolatey)

choco install yarn

Shell script (any Unix)

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

Verify the installation

yarn --version
1.23.0

Note

The exact strings Yarn uses to upgrade itself are tied to how it was installed (brew upgrade yarn, sudo apt-get update && sudo apt-get install yarn, choco upgrade yarn, and so on). When a newer release exists, Yarn prints the correct upgrade command for your installation method automatically the next time you run yarn install.


3. Core Concepts You Need to Know

Understanding five terms makes everything else in this guide click.

Term What it means
package.json Your project manifest. Declares the packages you depend on and the version ranges you accept.
yarn.lock The lockfile. Records the exact resolved version, source URL, and integrity hash of every package — direct and transitive. Commit this file.
Dependency types dependencies (needed at runtime), devDependencies (needed only to build/test), optionalDependencies (install failures are tolerated), peerDependencies (must be provided by the host project).
The cache A global, machine-wide folder where Yarn stores every package it has ever downloaded. Re-installs reuse the cache instead of hitting the network.
Hoisting Yarn flattens the dependency tree, lifting shared packages as high as possible in node_modules so they can be deduplicated.

Tip

Always commit yarn.lock to version control, including for libraries. It is the single source of truth that guarantees teammates and CI install byte-identical trees. The lockfile is human-readable but auto-generated — never edit it by hand.

For a deep dive into resolution, fetching, linking, hoisting, and the lockfile format, see How Yarn Works.


4. Everyday Usage

These are the commands you will reach for daily.

4.1 Installing dependencies

yarn install installs everything declared in package.json. It is the default command — running yarn with no arguments does exactly the same thing.

yarn install
# or simply:
yarn
yarn install v1.23.0
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
✨  Done in 5.82s.

The four phases you see correspond to Yarn's pipeline: resolve the graph, fetch packages into the cache, link them into node_modules, and build any packages with install scripts.

Useful install variants:

Command Use case
yarn install --frozen-lockfile CI builds. Fails if yarn.lock would need to change. Guarantees reproducibility.
yarn install --production Skip devDependencies — for deploying runtime-only artifacts.
yarn install --check-files Verify that the file tree in node_modules is intact and consistent.
yarn install --offline Error out if anything is missing from the local cache (no network).
yarn install --ignore-scripts Do not run any lifecycle/install scripts.
yarn install --force Re-fetch and re-build everything, overwriting the lockfile.

Warning

Use --frozen-lockfile in continuous integration. Without it, a stale or hand-edited yarn.lock can be silently regenerated during the build, masking the very drift you are trying to catch.

If a new install finds nothing to do, Yarn short-circuits:

success Already up-to-date.

4.2 Adding packages

yarn add installs one or more packages and writes them into your package.json.

# Add to "dependencies"
yarn add lodash

# Add a specific version or range
yarn add lodash@4.17.21
yarn add lodash@^4.0.0

# Add the latest release tagged "next"
yarn add lodash@next

Choose where the package is recorded with these flags:

Flag Short Effect
--dev -D Save to devDependencies.
--peer -P Save to peerDependencies.
--optional -O Save to optionalDependencies.
--exact -E Pin the exact version (1.2.3, no ^).
--tilde -T Use a tilde range (~1.2.3) — accept patch updates only.
--audit -A Run a vulnerability audit on the result.
--ignore-workspace-root-check -W Permit yarn add at the root of a workspaces project.
# Typical dev-tool install, pinned exactly
yarn add --dev --exact prettier
yarn add v1.23.0
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ prettier@3.2.5
✨  Done in 1.94s.

Note

By default Yarn records new packages with a caret range (^), controlled by the save-prefix setting (default ^). --exact produces no prefix; --tilde produces ~. If you set save-exact true in your config, every add becomes exact automatically.

Caution

Running yarn add <pkg> in the root of a workspaces monorepo is usually a mistake — root dependencies are shared by every workspace. Yarn blocks this unless you pass -W/--ignore-workspace-root-check.

4.3 Removing packages

yarn remove deletes one or more packages from package.json and yarn.lock, then re-installs so the tree is consistent.

yarn remove lodash
yarn remove lodash chalk           # remove several at once
yarn remove v1.23.0
[1/2] Removing module lodash...
[2/2] Regenerating lockfile and installing missing dependencies...
success Uninstalled packages.
✨  Done in 1.12s.

In a workspace root, the same -W/--ignore-workspace-root-check guard applies as with add.

4.4 Upgrading packages

There are three ways to move dependencies forward.

Upgrade within your declared ranges (the safe default — respects the ^/~ in package.json):

yarn upgrade                 # all packages
yarn upgrade lodash          # one package
yarn upgrade --scope @babel  # everything under a scope
yarn upgrade --pattern react # everything matching a pattern

Upgrade to the absolute latest (may cross major versions and rewrite ranges):

yarn upgrade --latest
yarn upgrade lodash --latest

When using --latest, control how the new range is written:

Flag Short Resulting range for 1.2.3
--caret -C ^1.2.3
--tilde -T ~1.2.3
--exact -E 1.2.3

Upgrade interactively — a checklist UI that lets you pick exactly which packages to bump:

yarn upgrade-interactive
yarn upgrade-interactive --latest
info Color legend :
 "<red>"    : Major Update backward-incompatible updates
 "<yellow>" : Minor Update backward-compatible features
 "<green>"  : Patch Update backward-compatible bug fixes
? Choose which packages to update. (Press <space> to select, <a> to toggle all)
❯◯  dependencies
    name       range   from     ❯  to       url
   ◯ lodash    ^4.17   4.17.15  ❯  4.17.21  https://github.com/lodash/lodash

Tip

Reach for yarn upgrade-interactive --latest during routine maintenance. The color-coded diff (red = major, yellow = minor, green = patch) makes it obvious which updates are risky before you commit to them.

4.5 Running scripts and binaries

yarn run executes a script defined in your package.json "scripts" block, or any binary installed under node_modules/.bin.

# These are equivalent:
yarn run build
yarn build            # the "run" is optional for non-reserved names
yarn run v1.23.0
$ webpack --mode production
... build output ...
✨  Done in 8.40s.

Pass arguments through to the underlying script after the script name:

yarn test --watch
yarn run lint --fix

List every available script by running yarn run with no arguments:

yarn run
info Commands available from binary scripts: eslint, prettier, webpack, ...
info Project commands
   - build
      webpack --mode production
   - test
      jest
question Which command would you like to run?:

Note

Yarn automatically runs matching pre and post scripts. Running yarn build will execute prebuild, then build, then postbuild if those scripts exist. Pass-through arguments are appended only to the main script, never to pre/post scripts.

Related execution commands:

Command What it does
yarn <script> Shorthand for yarn run <script>. If the name is not a known Yarn command, Yarn treats it as a script.
yarn exec <cmd> Run an arbitrary command inside Yarn's environment (with node_modules/.bin on PATH).
yarn bin [<name>] Print the path to the .bin folder, or to a specific binary.
yarn node [args] Run Node using the same version Yarn uses, from the project root (auto-loads PnP if enabled).
# Print where a binary lives
yarn bin eslint
/home/you/project/node_modules/.bin/eslint

4.6 Inspecting your project

Command Purpose
yarn list Print the installed dependency tree.
yarn list --depth=0 Top-level dependencies only.
yarn list --pattern <glob> Filter the tree by package name.
yarn why <package> Explain why a package is installed and who depends on it.
yarn outdated [pkgs] Show packages with newer versions available.
yarn info <package> Show registry metadata for any package.
yarn versions Show versions of Yarn, Node, and their components.
yarn check Verify that node_modules matches package.json and yarn.lock.
yarn why lodash
yarn why v1.23.0
[1/4] Why do we have the module "lodash"...?
[2/4] Initialising dependency graph...
[3/4] Finding dependency...
[4/4] Calculating file sizes...
=> Found "lodash@4.17.21"
info Reasons this module exists
   - "webpack" depends on it
   - Hoisted from "webpack#lodash"
info Disk size without dependencies: "1.41MB"
info Disk size with unique dependencies: "1.41MB"
info Disk size with transitive dependencies: "1.41MB"
info Number of shared dependencies: 0
✨  Done in 0.84s.
yarn outdated
yarn outdated v1.23.0
info Color legend :
 "<red>"    : Major Update backward-incompatible updates
 "<yellow>" : Minor Update backward-compatible features
 "<green>"  : Patch Update backward-compatible bug fixes
Package  Current  Wanted   Latest   Package Type   URL
lodash   4.17.15  4.17.21  4.17.21  dependencies   https://github.com/lodash/lodash
✨  Done in 0.97s.

5. Common Workflows

Recipes that combine the everyday commands.

Set up a brand-new project

mkdir my-app && cd my-app
yarn init -y                      # create package.json with defaults
yarn add express                  # runtime dependency
yarn add --dev nodemon jest       # dev tooling

Reproduce a teammate's environment exactly

git clone <repo> && cd <repo>
yarn install --frozen-lockfile    # install the locked tree, fail on drift

Clean reinstall (when node_modules is corrupted)

# Unix
rm -rf node_modules
yarn install --force

Deploy a production build

yarn install --frozen-lockfile --production

This installs only dependencies (no dev tooling) and refuses to touch the lockfile.

Audit and patch vulnerabilities

yarn audit                        # report known vulnerabilities
yarn upgrade-interactive --latest # selectively bump the flagged packages

Trim the on-disk footprint of node_modules

yarn autoclean --init             # create a .yarnclean filter file
yarn autoclean --force            # delete docs, tests, examples from deps

Caution

yarn autoclean permanently deletes files (READMEs, tests, examples, CI configs) from inside your installed packages to save space. It is irreversible until the next install. Review the generated .yarnclean before running --force.


6. Workspaces (Monorepos)

Workspaces let a single repository contain multiple packages that depend on each other, sharing one node_modules and one lockfile. Declare them in the root package.json:

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

Important

The root of a workspaces project must be marked "private": true. Yarn refuses to treat a publishable package as a workspace root.

A single yarn install at the root installs and links every workspace at once. Local packages that depend on each other are symlinked instead of downloaded.

Inspect your workspaces

yarn workspaces info
{
  "package-a": {
    "location": "packages/package-a",
    "workspaceDependencies": ["package-b"],
    "mismatchedWorkspaceDependencies": []
  },
  "package-b": {
    "location": "packages/package-b",
    "workspaceDependencies": [],
    "mismatchedWorkspaceDependencies": []
  }
}

Run a command in one workspace

# yarn workspace <workspace-name> <command> [args]
yarn workspace package-a add lodash
yarn workspace package-a run build

Run a script across every workspace

yarn workspaces run test

This runs yarn run test inside each workspace in turn.

Focus on a single workspace

yarn install --focus

--focus installs remote copies of a workspace's siblings instead of symlinking them — useful when you want to build or test one package in isolation.


7. Publishing Packages

yarn publish bumps the version, packs the package, and uploads it to the npm registry.

yarn publish                       # interactive version prompt
yarn publish --new-version 2.0.0   # set the version explicitly
yarn publish --tag next            # publish under a dist-tag other than "latest"
yarn publish --access public       # publish a scoped package publicly

The command runs in four steps:

[1/4] Bumping version...
[2/4] Logging in...
[3/4] Publishing...
[4/4] Revoking token...
success Published.

Note

You must be authenticated to publish. Run yarn login first to store your registry username and email, or set a YARN_AUTH_TOKEN / NPM_AUTH_TOKEN environment variable, or configure an _authToken in .npmrc. If two-factor authentication is enabled, Yarn prompts for a one-time password (or pass --otp <code>).

Warning

Yarn refuses to publish a package whose package.json has "private": true. This is a safety guard against accidentally publishing internal code.

Version management

yarn version bumps the version in package.json and (by default) creates a git commit and tag.

yarn version --new-version 1.4.0
yarn version --major     # 1.4.0 -> 2.0.0
yarn version --minor     # 1.4.0 -> 1.5.0
yarn version --patch     # 1.4.0 -> 1.4.1
yarn version --premajor --preid beta   # 1.4.0 -> 2.0.0-beta.0
Flag Effect
--new-version <v> Set an explicit version.
--major / --minor / --patch Auto-increment that component.
--premajor / --preminor / --prepatch / --prerelease Auto-increment a pre-release.
--preid <id> Identifier for the pre-release (e.g. beta).
--message <msg> Custom commit message (%s is replaced by the version).
--no-git-tag-version Bump the version but do not create a git commit/tag.
--no-commit-hooks Bypass git hooks when committing.

Pre-publishing helpers

Command Purpose
yarn pack Create a .tgz archive of the package exactly as it would be published — without uploading. Inspect it before you ship.
yarn pack --filename out.tgz Write the archive to a specific filename.

Managing the published package

Command Purpose
yarn owner list <pkg> List package maintainers.
yarn owner add <user> <pkg> Add a maintainer.
yarn owner remove <user> <pkg> Remove a maintainer.
yarn tag add <pkg>@<version> <tag> Point a dist-tag at a version.
yarn tag list [<pkg>] List dist-tags.
yarn tag remove <pkg> <tag> Delete a dist-tag.
yarn team create <scope:team> Create an org team.
yarn team add <scope:team> <user> Add a user to a team.
yarn team list <scope> List teams or members.

8. Global Packages

yarn global installs command-line tools available system-wide, outside any project.

yarn global add create-react-app
yarn global add typescript@5.0.0
yarn global list
yarn global upgrade typescript
yarn global remove create-react-app

Find out where global tools and their binaries live:

yarn global bin    # the folder added to your PATH
yarn global dir    # the folder holding global packages

Tip

If a globally installed command "isn't found" after install, the global bin folder (yarn global bin) is probably not on your PATH. Add it to your shell profile. On Windows the default location is %LOCALAPPDATA%\Yarn\bin; on Unix it is typically /usr/local/bin or ~/.yarn/bin.

Caution

Do not yarn global add yarn. Yarn warns you if you try — manage Yarn itself through your OS package manager or the per-project yarn set version mechanism instead.

yarn create — scaffold from a starter kit

yarn create is a shortcut that globally installs a create-* package and runs it in one step:

yarn create react-app my-app
# equivalent to: yarn global add create-react-app && create-react-app my-app

When you are developing a library and an app that consumes it simultaneously, yarn link lets the app use your in-progress library via a symlink.

# In the library you are developing:
cd ~/my-library
yarn link
success Registered "my-library".
info You can now run `yarn link "my-library"` in the projects where you want to use this package and it will be used instead.
# In the consuming app:
cd ~/my-app
yarn link my-library

When you are done, reverse it:

# In the app:
yarn unlink my-library
# In the library:
yarn unlink
# Then reinstall the real dependency in the app:
yarn install --force

Note

After yarn unlink-ing a package in your app, run yarn install --force to restore the real published version from the registry. Unlinking only removes the symlink; it does not re-fetch the package.


10. Security & Auditing

yarn audit checks your installed dependency tree against the registry's vulnerability database.

yarn audit
yarn audit --summary                  # just the totals
yarn audit --level high               # only high+ severity
yarn audit --groups dependencies      # restrict which dependency groups to scan
yarn audit v1.23.0
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ high          │ Prototype Pollution                                            │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ lodash                                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=4.17.21                                                      │
└───────────────┴──────────────────────────────────────────────────────────────┘
1 vulnerability found - Packages audited: 412
Severity: 1 High

You can also run an audit as part of any install or upgrade by adding -A/--audit:

yarn install --audit
yarn add lodash --audit

Important

yarn audit exits with a non-zero status code that encodes the severities found (info=1, low=2, moderate=4, high=8, critical=16, summed together). This lets CI pipelines fail a build when vulnerabilities at or above a chosen level are present. A clean audit exits 0.


11. Advanced Usage

Plug'n'Play (PnP)

Yarn 1 includes an experimental installation strategy that skips node_modules entirely, resolving packages straight from the cache through a generated .pnp.js file.

yarn install --enable-pnp     # or --pnp
yarn install --disable-pnp

When PnP is enabled, yarn unplug temporarily extracts a package to a real folder so you can patch or debug it:

yarn unplug lodash
yarn unplug lodash --clear        # remove a specific unplugged package
yarn unplug --clear-all           # remove all unplugged packages

Note

yarn unplug only works when Plug'n'Play is enabled. Without PnP it errors with Packages can only be unplugged when Plug'n'Play is enabled.

Offline / air-gapped installs

Configure an offline mirror so every downloaded tarball is saved next to your project, enabling fully offline installs:

yarn config set yarn-offline-mirror ./npm-packages-offline-cache
yarn config set yarn-offline-mirror-pruning true
yarn install                          # populates the mirror
# later, on an air-gapped machine:
yarn install --offline                # uses only the mirror, no network

Importing from npm

If you have an npm project and want to adopt Yarn without changing resolved versions, yarn import generates a yarn.lock from an existing package-lock.json or node_modules:

yarn import

Single-instance mutex

Prevent two Yarn processes from running at once (useful in scripted environments):

yarn install --mutex file
yarn install --mutex network:31997

Capturing network traffic

yarn install --har        # writes a yarn-install_<timestamp>.har file

12. Global Flags Reference

These flags can be combined with any command. They are parsed before the command name.

Network

Flag Description
--registry <url> Override the configured registry.
--offline Error if any required dependency is not in the local cache.
--prefer-offline Use the network only for dependencies missing from the cache.
--proxy <host> HTTP proxy.
--https-proxy <host> HTTPS proxy.
--network-concurrency <n> Max simultaneous network requests (default 8).
--network-timeout <ms> Per-request TCP timeout (default 30000).
--har Save a HAR capture of all network traffic.

Lockfile & integrity

Flag Description
--frozen-lockfile Do not generate a lockfile; fail if an update is needed.
--pure-lockfile Do not generate a lockfile.
--no-lockfile Do not read or generate a lockfile.
--update-checksums Update package checksums from the current repository.
--check-files Verify the file tree of installed packages for consistency.
--skip-integrity-check Skip the check that decides whether reinstall is needed.

Installation behavior

Flag Description
--production, --prod [bool] Skip devDependencies.
--flat Allow only a single version of each package (prompts on conflicts).
--force Re-fetch and rebuild everything; overwrite the lockfile.
--ignore-scripts Do not run lifecycle scripts.
--ignore-engines Ignore engines compatibility checks.
--ignore-platform Ignore os/cpu platform checks.
--ignore-optional Do not install optional dependencies.
--no-bin-links Do not create .bin symlinks.
--link-duplicates Hard-link duplicated modules instead of copying.

Folders & cache

Flag Description
--cache-folder <path> Force a specific cache folder.
--preferred-cache-folder <path> Preferred cache folder (falls back if unusable).
--global-folder <path> Where global packages are stored.
--link-folder <path> Where global links are stored.
--modules-folder <path> Output modules here instead of ./node_modules.
--cwd <dir> Working directory to run in.

Output & interaction

Flag Description
--silent, -s Suppress Yarn's own logs (script output still prints).
--verbose Print verbose internal operation logs.
--json Emit all log messages as newline-delimited JSON.
--no-progress Disable progress bars.
--emoji [bool] Toggle emoji in output.
--non-interactive Never show interactive prompts.
-v, --version Print the Yarn version.
-h, --help Show help (works after any command).

Yarn resolution & PnP

Flag Description
--enable-pnp, --pnp Enable Plug'n'Play.
--disable-pnp Disable Plug'n'Play.
--focus Install remote copies of sibling workspaces.
--otp <code> One-time password for 2FA.
--use-yarnrc <path> Use a specific .yarnrc file.
--no-default-rc Do not auto-detect .yarnrc/.npmrc files.
--no-node-version-check Do not warn about unsupported Node versions.

13. Configuration (.yarnrc)

Yarn reads configuration from .yarnrc files (Yarn-specific) and .npmrc files (shared with npm), searched from your project directory up to your home directory. Manage settings with yarn config:

yarn config list                  # show effective Yarn + npm config
yarn config get <key>             # read one value
yarn config set <key> <value>     # write to ~/.yarnrc
yarn config delete <key>          # remove a setting
yarn config set save-prefix '~'
yarn config set init-license 'Apache-2.0'

Common settings and their defaults:

Setting Default Purpose
save-prefix ^ Range prefix used by yarn add.
init-version 1.0.0 Default version for yarn init.
init-license MIT Default license for yarn init.
version-tag-prefix v Git tag prefix for yarn version.
version-git-tag true Whether yarn version creates a git tag.
version-commit-hooks true Whether git commit hooks run on yarn version.
version-git-message v%s Commit message template for yarn version.
bin-links true Whether to create .bin links.
ignore-scripts false Whether to skip lifecycle scripts.
ignore-optional false Whether to skip optional dependencies.
registry https://registry.yarnpkg.com Package registry URL.
strict-ssl true Enforce valid TLS certificates.

Note

A complete configuration reference — including authentication keys, offline-mirror settings, scoped registries, and every environment variable Yarn reads — lives in the Admin Guide. This section covers the settings most users touch day to day.


14. How Yarn Works

A high-level mental model. (For the full architecture, module-by-module, see the Admin Guide.)

Every install moves through a deterministic pipeline:

package.json ──> 1. RESOLVE ──> 2. FETCH ──> 3. LINK ──> 4. BUILD ──> node_modules + yarn.lock
  1. Resolve — Yarn reads your manifests, expands every version range against the registry (or the lockfile, if present), and computes the complete dependency graph including transitive packages. The result is pinned in yarn.lock.
  2. Fetch — Each resolved package is downloaded once into the global cache and verified against an integrity hash (sha512/sha1). Subsequent installs reuse the cache.
  3. Link — Packages are copied (or symlinked, for link:/workspace: dependencies) into node_modules. During linking Yarn hoists shared packages as high as possible to deduplicate them.
  4. Build — Packages with install scripts (preinstall, install, postinstall) are compiled. Skip with --ignore-scripts.

The lockfile (yarn.lock) is the contract that makes installs reproducible. For each pattern (e.g. lodash@^4.0.0) it records the resolved version, the source URL, and an integrity hash. Yarn's lockfile is version 1 and uses a custom, human-readable format — but it is auto-generated, so never edit it by hand. Yarn can even resolve git merge conflicts inside a lockfile automatically by merging both sides.

Yarn supports many package sources beyond the npm registry. A dependency range can point to:

Source Example value
npm registry lodash@^4.17.0
Git git+https://github.com/user/repo.git#branch
GitHub shorthand user/repo#commit
GitLab / Bitbucket gitlab:user/repo, bitbucket:user/repo
Gist gist:hash
Tarball URL https://example.com/pkg.tgz
Local file file:../local-package
Local symlink link:../local-package

15. Troubleshooting

Error: Your lockfile needs to be updated, but yarn was run with '--frozen-lockfile'.

Cause: yarn.lock is out of sync with package.json, and --frozen-lockfile forbids regenerating it. Common in CI after someone edited package.json without committing the updated lockfile. Solution: Locally run yarn install (no --frozen-lockfile), then commit the regenerated yarn.lock. Prevention: Always commit package.json and yarn.lock together in the same change.

Error: error An unexpected error occurred: ... unable to get local issuer certificate

Cause: Yarn cannot validate the registry's TLS certificate, typically behind a corporate proxy that injects its own CA (community issue #841). Solution: Point Yarn at your corporate CA bundle: yarn config set cafile /path/to/ca.pem, or set the --https-proxy flag. As a last resort yarn config set strict-ssl false (insecure — avoid in production). Prevention: Provision the corporate CA certificate on developer and CI machines.

Error: yarn audit failing due to 410 error

Cause: The audit endpoint returned HTTP 410 Gone — usually a custom/proxy registry that does not implement the npm audit API (community issue #9234). Solution: Run audits against a registry that supports the audit endpoint, or skip auditing in that environment. Audit failures do not block installs unless you passed --audit. Prevention: Configure yarn audit only where the registry supports it.

Error: bundledDependencies attempted to be fetched from npm instead

Cause: A package declares bundledDependencies that Yarn tried to resolve from the registry (community issue #5998). Solution: Ensure the bundling package ships its bundled deps in its tarball; re-run with --force to rebuild the integrity state. Prevention: Verify bundled packages with yarn pack before publishing.

Error: Couldn't find package "X" ... on the "npm" registry

Cause: The package name is misspelled, private, or your registry/scope configuration points elsewhere. Solution: Check the name with yarn info <pkg>. For scoped/private packages, configure the scope's registry and an auth token in .npmrc. Prevention: Use yarn config get registry to confirm where Yarn is looking.

Command exits with code 3221226525 on Windows

Cause: A native crash (stack overflow / access violation) in a child process during install, often from an incompatible native module (community issue #8099). Solution: Rebuild native modules with a matching Node/Python/build-tools version; clear the cache with yarn cache clean and reinstall. Prevention: Keep build toolchains aligned with the Node version in engines.

node_modules looks wrong / packages missing

Cause: Partial or interrupted install, or a corrupted cache. Solution: Run yarn check to diagnose, then rm -rf node_modules && yarn install --force. If problems persist, yarn cache clean and reinstall. Prevention: Let installs finish; avoid killing Yarn mid-run.

'Can't answer a question unless a user TTY'

Cause: Yarn needs interactive input but is running in a non-interactive context (CI, piped output) — community issue #7248. Solution: Pass --non-interactive and provide answers via flags (e.g. yarn init -y, --new-version, --otp). Prevention: Script Yarn with explicit flags in automated environments.

Globally installed CLI is "command not found"

Cause: The global bin folder is not on PATH. Solution: Run yarn global bin and add that directory to your shell profile / system PATH. Prevention: Configure PATH once when you first install Yarn.

Yarn warns it is outdated

Cause: Yarn checks for a newer version once a day and nags if one exists. Solution: Upgrade using the command Yarn prints for your install method (brew upgrade yarn, npm i -g yarn, etc.). Prevention: Disable the check with yarn config set disable-self-update-check true if you manage Yarn centrally.

DeprecationWarning for url.parse on Node 24

Cause: Yarn 1 uses the legacy url.parse API, deprecated in newer Node releases (community issue #9210). Solution: The warning is harmless. To silence it, run with NODE_OPTIONS=--no-deprecation, or migrate to Yarn 2+. Prevention: N/A — cosmetic warning only.


16. FAQ

Q: Do I need to commit yarn.lock? Yes — always, for both applications and libraries. It is what guarantees reproducible installs.

Q: What is the difference between yarn and yarn install? Nothing. install is the default command, so bare yarn runs it.

Q: yarn add vs yarn install? yarn add <pkg> installs a new package and records it in package.json. yarn install installs what is already declared.

Q: Can I use Yarn and npm in the same project? You can, but don't. Mixing yarn.lock and package-lock.json leads to divergent trees. Pick one tool per project.

Q: What does --frozen-lockfile do? It installs the exact tree in yarn.lock and fails if the lockfile would need to change — the correct setting for CI.

Q: How do I install only production dependencies? yarn install --production (or set NODE_ENV=production). This skips devDependencies.

Q: How do I run a package.json script? yarn run <script>, or just yarn <script> for any name that isn't a built-in Yarn command.

Q: How do I pass flags to a script? Put them after the script name: yarn test --watch. They are appended to the script command.

Q: Why is a package installed? Who depends on it? yarn why <package> traces the reasons and shows disk usage.

Q: What is hoisting? Yarn lifts shared dependencies to the top of node_modules so multiple packages can share one copy, reducing duplication.

Q: Where is the global cache? Run yarn cache dir to print its location. Clear it with yarn cache clean.

Q: How do I upgrade Yarn itself? Use your OS package manager, or pin a version per-project with yarn set version <range> (see below). Don't yarn global add yarn.

Q: What's the difference between dependencies and devDependencies? dependencies are needed when your code runs in production; devDependencies are only needed to build and test. Use yarn add --dev for the latter.

Q: How do I update to the latest major versions of everything? yarn upgrade-interactive --latest and select the packages you want.

Q: Is Yarn 1 still maintained? Yarn 1 (Classic) is stable and widely used but in maintenance mode; new features land in Yarn 2+ ("Berry"). Migrate with yarn set version berry when ready.


Upgrading Yarn itself

Yarn can pin a specific release per project, committing it to the repo so everyone uses the same version:

yarn policies set-version latest    # pin the latest 1.x
yarn policies set-version 1.22.19   # pin an exact version
yarn set version berry              # migrate to Yarn 2+ (writes .yarnrc.yml)
yarn init -2                        # scaffold a new project on Yarn 2

Note

yarn set version is an alias for yarn policies set-version. It downloads the requested Yarn bundle into .yarn/releases/ and points .yarnrc (or .yarnrc.yml for v2+) at it via the yarn-path setting, so the project always runs that exact Yarn — independent of the globally installed version.


17. Command Reference

Every Yarn command at a glance. Run yarn help <command> for full details on any one.

Command Description
yarn / yarn install Install all dependencies from package.json.
yarn add <pkg...> Add packages and save to package.json.
yarn remove <pkg...> Remove packages from package.json and yarn.lock.
yarn upgrade [pkg...] Upgrade packages within their declared ranges.
yarn upgrade-interactive Interactively select packages to upgrade.
yarn init Create or update a package.json interactively.
yarn run <script> Run a package.json script or a .bin binary.
yarn exec <cmd> Run a command in Yarn's environment.
yarn node [args] Run Node with Yarn's version/PnP from the project root.
yarn bin [name] Print the .bin folder, or the path to a binary.
yarn list Print the dependency tree.
yarn why <pkg> Explain why a package is installed.
yarn outdated [pkg...] Show packages with newer versions available.
yarn info <pkg> [field] Show registry metadata for a package.
yarn check Verify node_modules against package.json/yarn.lock.
yarn audit Report known security vulnerabilities.
yarn licenses list List licenses of installed packages.
yarn licenses generate-disclaimer Emit an attribution/notice document.
yarn cache list List packages in the global cache.
yarn cache dir Print the cache folder path.
yarn cache clean [pkg...] Remove packages from the cache.
yarn autoclean Strip unnecessary files from dependencies.
yarn import Generate yarn.lock from npm's package-lock.json/node_modules.
yarn pack Create a publishable .tgz without uploading.
yarn publish Publish the package to the registry.
yarn version Bump the package version (and git tag).
yarn versions Show Yarn, Node, and component versions.
yarn login Store registry username and email.
yarn logout Clear stored registry credentials.
yarn owner Manage package maintainers.
yarn tag Manage dist-tags on a package.
yarn team Manage org team memberships.
yarn global <add|remove|list|upgrade|bin|dir> Manage globally installed packages.
yarn create <starter> Scaffold a project from a create-* package.
yarn link / yarn unlink Create/remove a development symlink.
yarn workspace <name> <cmd> Run a command in one workspace.
yarn workspaces <info|run> Inspect or run scripts across all workspaces.
yarn config <get|set|delete|list> Manage configuration.
yarn policies set-version <range> Pin the Yarn version for the project.
yarn set version <range> Alias for policies set-version.
yarn unplug <pkg...> Extract a package from the cache (PnP only).
yarn generate-lock-entry Print a lockfile entry for the current package.
yarn help [command] Show help.

Note

A few legacy commands are intentionally no-ops in Yarn, because yarn install handles them automatically: yarn dedupe ("isn't necessary — yarn install will already dedupe"), yarn prune ("yarn install will prune extraneous packages"), and yarn lockfile ("yarn install will produce a lockfile"). The yarn access command is reserved but not yet implemented.