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:
- Parallel Installation: Yarn supports parallel dependency installation, allowing multiple packages to be installed simultaneously, significantly speeding up the process.
- Deterministic Installation: Yarn uses a
yarn.lockfile to ensure consistent dependency installations across environments, addressing npm’s inconsistency issues due to version differences. - Offline Mode: Yarn caches installed packages, enabling fast installations from local cache even in unstable network conditions.
- Faster Recovery: Yarn recovers faster than npm by skipping already-installed packages and only installing those not yet present.
- Better User Experience: Yarn offers detailed command-line output and additional commands like
yarn whyandyarn outdated, helping developers better understand and manage dependencies.
Core Features and Advantages
- Performance: Parallel installation and caching mechanisms drastically improve installation speed, especially in large projects.
- Consistency: The
yarn.lockfile ensures identical dependency installations across all developers and environments, avoiding version conflicts. - Offline Mode: Yarn can install dependencies from local cache without an internet connection.
- Predictability: Yarn’s installation process is predictable, reducing differences between development and production environments.
- Ease of Use: Yarn’s command-line interface is intuitive, offering rich commands and options for efficient project management.
- Compatibility: Yarn is compatible with npm’s
package.jsonfiles, 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 yarnThis installs Yarn globally. Verify the installation with:
yarn --version2. 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 yarnto 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.org4. 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 4Using Yarn
1. Initialize a Project
Create a package.json file:
yarn init2. Add Dependencies
Add a dependency:
yarn add <package-name>3. List Dependencies
View all project dependencies:
yarn list4. 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 initAdd 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 versionRemove 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 versionDowngrade 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 listCheck Dependencies
yarn check
Verifies that installed dependencies match the yarn.lock file.
yarn checkClear Cache
yarn cache clean
Clears Yarn’s cache, useful for resolving installation issues or forcing redownloads.
yarn cache cleanView 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 definedList Outdated Dependencies
yarn outdated
Lists dependencies with available updates.
yarn outdatedDeduplicate Dependencies
yarn dedupe
Optimizes the dependency tree by reducing duplicates.
yarn dedupeTrace 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 installLocate Executable Scripts
yarn bin
Displays the path to executable scripts, useful for globally installed packages.
yarn binCheck Version
yarn --version
Shows the current Yarn version.
yarn --versionAccess Help
yarn help
Displays help documentation for all available commands.
yarn helpUse Cases
- Project Initialization: Use
yarn initto createpackage.json. - Dependency Management: Use
yarn add,yarn upgrade,yarn remove, andyarn dedupe. - Script Execution: Run project scripts with
yarn <script-name>. - Version Control: Ensure dependency consistency with
yarn check. - Troubleshooting: Use
yarn whyandyarn outdatedto 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 initAdd Dependencies
Use yarn add to include required dependencies. For example, to add the Express framework:
yarn add expressThis 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 startThis 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 loginFollow prompts to enter your npm username, password, and email.
Publish the Package
Publish the package with:
npm publishNote: Yarn does not directly support the publish command, but npm’s publish command is compatible, as Yarn and npm share the same publishing workflow.



