CentOSRHEL Based

How To Install Yarn on CentOS Stream 10

Install Yarn on CentOS Stream 10

Yarn has quickly become an essential tool for JavaScript developers due to its improved performance, security features, and enhanced dependency management capabilities. If you’re running CentOS Stream 10 and need to work with Node.js applications, installing Yarn can significantly streamline your development workflow. This comprehensive guide will walk you through the complete process of installing Yarn on CentOS Stream 10, exploring multiple installation methods, configuration options, and best practices to ensure you get the most out of this powerful package manager.

Understanding Yarn and Its Benefits

Yarn, which stands for “Yet Another Resource Navigator,” was developed by Facebook in 2016 as an alternative to npm (Node Package Manager). While both tools serve the same fundamental purpose—managing JavaScript dependencies—Yarn offers several distinct advantages that have made it increasingly popular among developers.

Superior Performance

One of the most compelling reasons to use Yarn is its speed. Yarn employs parallel operations when installing packages, which significantly reduces installation time compared to npm. Additionally, Yarn’s sophisticated caching mechanism stores previously downloaded packages locally, eliminating the need to re-download them during future installations. This feature is particularly beneficial for developers working with large projects or in environments with limited internet connectivity.

Enhanced Security Features

Security is another area where Yarn excels. It uses checksums to verify the integrity of every installed package, ensuring that what you’re installing hasn’t been tampered with. This verification process helps protect your projects from potentially malicious code that could be introduced through compromised packages.

Deterministic Installations

Yarn creates a detailed lockfile (yarn.lock) that specifies exactly which versions of each dependency are installed. This ensures that all team members and deployment environments use identical package versions, eliminating the “works on my machine” problem that can plague development teams. The deterministic nature of Yarn installations reduces bugs and inconsistencies across different environments.

Improved Offline Capabilities

With its robust caching system, Yarn allows you to install packages even without an internet connection, provided you’ve downloaded them at least once before. This offline capability can be invaluable when working in environments with unreliable internet or when traveling.

Prerequisites for Installation

Before proceeding with Yarn installation on CentOS Stream 10, ensure your system meets all the necessary requirements. Taking the time to prepare your environment will help avoid potential issues during the installation process.

System Requirements

CentOS Stream 10 should meet the following basic requirements:

  • A minimum of 2GB RAM (4GB recommended for development environments)
  • At least 20GB of free disk space
  • A stable internet connection for downloading packages

Required Permissions

You’ll need either root access or sudo privileges to install Yarn system-wide. If you’re working in a shared environment where you don’t have administrative rights, you can still install Yarn locally within your user account using the npm method.

Node.js and NPM Installation

Since Yarn is a JavaScript package manager, having Node.js and npm already installed on your system is essential for certain installation methods. You can verify if they’re installed by running:

node -v
npm -v

If these commands don’t return version numbers, you’ll need to install Node.js and npm first. You can do this through various methods, including the EPEL repository:

sudo dnf install epel-release
sudo dnf module install nodejs

After installation, verify that Node.js is properly installed:

node --version

System Updates

Before installing any new software, it’s good practice to ensure your system is up-to-date:

sudo dnf update

This command updates all installed packages to their latest versions, which can help prevent compatibility issues.

Method 1: Installing Yarn via NPM

The simplest way to install Yarn on CentOS Stream 10 is through npm, especially if you already have Node.js installed on your system. This method is straightforward and works well for most development scenarios.

Step 1: Verify Node.js and NPM Installation

Before proceeding, confirm that Node.js and npm are installed on your system by checking their versions:

node -v
npm -v

If you see version numbers displayed, you’re ready to install Yarn. If not, refer to the prerequisites section to install Node.js and npm.

Step 2: Install Yarn Globally Using NPM

To make Yarn available system-wide, install it globally using npm with the following command:

sudo npm install -g yarn

The -g flag indicates a global installation, allowing Yarn to be used from any directory on your system. If you only need Yarn for a specific project, you can omit this flag and install it locally within that project.

Step 3: Verify the Installation

After the installation completes, verify that Yarn was installed correctly by checking its version:

yarn --version

If the command displays a version number (like 1.22.21), Yarn has been successfully installed on your system.

Advantages of NPM Installation

Installing Yarn via npm is often the quickest method and ensures compatibility with your Node.js version. It’s particularly useful for development environments where you’re frequently working with JavaScript projects.

Method 2: Installing Yarn via DNF and Repository

For a more integrated installation that leverages CentOS’s native package management system, you can install Yarn using DNF and the official Yarn repository. This method is recommended for production environments and system-wide installations.

Step 1: Update Your System

Start by ensuring your system packages are up-to-date:

sudo dnf update

This reduces the risk of conflicts during installation.

Step 2: Add the Yarn Repository

Add the official Yarn repository to your system’s package sources:

curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo

This command downloads the repository configuration file and saves it to the appropriate location.

Step 3: Import the GPG Key

Import the repository’s GPG key to verify package authenticity:

sudo rpm --import https://dl.yarnpkg.com/rpm/pubkey.gpg

This step ensures that all packages downloaded from the Yarn repository are genuine and haven’t been tampered with.

Step 4: Verify Repository Availability

Confirm that the Yarn package is available in the added repository:

sudo dnf list available | grep yarn

You should see yarn listed among the available packages.

Step 5: Install Yarn

With the repository properly configured, install Yarn using dnf:

sudo dnf install yarn

This command will download and install the latest version of Yarn from the official repository.

Step 6: Verify the Installation

After installation, verify that Yarn is installed correctly by checking its version:

yarn --version

A successful installation will display the installed version number.

Method 3: Installing Yarn via cURL Script

Another flexible method for installing Yarn on CentOS Stream 10 is using the official installation script. This approach is particularly useful for user-specific installations or when you need more control over the installation process.

Step 1: Download and Execute the Installation Script

Download and run the official Yarn installation script:

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

This script downloads the latest version of Yarn and installs it in the .yarn directory within your home folder.

Step 2: Set Up Environment Variables

The installation script automatically attempts to add Yarn to your PATH. However, you may need to manually configure your shell environment by adding the following line to your .bashrc or .zshrc file:

export PATH="$HOME/.yarn/bin:$HOME/.config/yarn/global/node_modules/.bin:$PATH"

After modifying your shell configuration file, reload it:

source ~/.bashrc   # or source ~/.zshrc if you're using Zsh

Step 3: Verify the Installation

Confirm that Yarn is installed correctly by checking its version:

yarn --version

If the command returns a version number, the installation was successful.

Benefits of Script Installation

The script installation method offers several advantages:

  • It installs Yarn only for the current user, which is ideal for shared systems
  • It doesn’t require administrative privileges
  • It automatically updates PATH variables
  • It can be easily automated in deployment scripts

Configuration After Installation

Once Yarn is installed on your CentOS Stream 10 system, configuring it to match your workflow can significantly enhance your productivity. Proper configuration ensures Yarn works optimally within your development environment.

Global Configuration Settings

Yarn allows you to set global configuration options that apply to all projects. To view current global settings:

yarn config list

To set a global configuration option:

yarn config set <key> <value>

Common global configurations include:

yarn config set init-license MIT
yarn config set init-version 0.1.0

These settings define default values for new projects.

Environment Variables Setup

Several environment variables can control Yarn’s behavior. The most important is PATH, which should include Yarn’s binary location. For script installations, this should already be configured, but you can verify by running:

echo $PATH | grep yarn

If Yarn’s path isn’t listed, add it as shown in the script installation section.

User vs. System-wide Configuration

Yarn stores configuration in two places:

  • User-specific settings: ~/.yarnrc.yml
  • Project-specific settings: .yarnrc.yml in the project directory

User settings apply to all your projects, while project settings override user settings for that specific project. This hierarchy allows for flexible configuration management across different projects.

Path Configuration

You can configure where Yarn stores global packages using:

yarn config set global-folder /path/to/global/packages

This is particularly useful in environments where disk space is allocated differently across file systems.

Package Defaults and Preferences

Set your preferred package versions and other defaults:

yarn config set save-prefix "~"  # Use tilde for version ranges
yarn config set save-exact true  # Save exact versions instead of ranges

These settings help maintain consistent dependencies across development environments.

Basic Yarn Commands and Usage

Mastering the essential Yarn commands will help you efficiently manage JavaScript packages in your projects. This section covers the fundamental operations you’ll perform regularly.

Project Initialization

To start a new project with Yarn:

mkdir my_project
cd my_project
yarn init

This command launches an interactive process that creates a package.json file with your project’s metadata. For a quick setup with default values, use yarn init -y.

Adding Dependencies

To add a package to your project:

yarn add [package-name]

This command installs the package and adds it to your package.json file as a dependency. For development dependencies:

yarn add [package-name] --dev

To specify a particular version:

yarn add [package-name]@[version]

For example:

yarn add express
yarn add jest --dev
yarn add react@17.0.2

These commands will install the specified packages and update your project’s dependency list.

Removing Packages

To remove a package:

yarn remove [package-name]

This command uninstalls the package and removes it from your package.json.

Installing All Dependencies

When you clone a project or pull changes that include new dependencies, install all packages listed in package.json:

yarn install

Or simply:

yarn

This command reads the package.json file and installs all required dependencies. If a yarn.lock file exists, Yarn will use it to ensure exact versions are installed.

Updating Packages

To update dependencies to their latest versions within the constraints specified in package.json:

yarn upgrade

To upgrade a specific package:

yarn upgrade [package-name]

These commands update packages while respecting your version constraints.

Advanced Usage Scenarios

As your projects grow more complex, Yarn offers advanced features to handle sophisticated dependency management scenarios. These features are particularly valuable for larger applications and team environments.

Working with Workspaces for Monorepos

Yarn workspaces allow you to manage multiple projects within a single repository, sharing dependencies and simplifying cross-project development:

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

With this configuration, all projects in the packages directory can share dependencies, reducing duplication and simplifying version management.

Offline Installation Techniques

Yarn’s offline capability is invaluable in environments with limited connectivity. To enable offline mode:

yarn --offline

For a fully offline workflow, first ensure your cache contains all necessary packages by running installations while connected, then use the offline flag when disconnected.

Custom Scripts and Automation

Define custom scripts in your package.json to automate common tasks:

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

Run these scripts using:

yarn run start

Or the shorthand:

yarn start

These scripts significantly streamline development workflows by providing consistent commands across team members.

Version Locking Strategies

For production environments, exact version locking is crucial. Yarn’s lockfile (yarn.lock) automatically ensures this, but you can also enforce exact versions in package.json:

yarn config set save-exact true

This configuration prevents unexpected behavior due to dependency updates.

Performance Optimization Tips

To maximize Yarn’s performance:

  • Use the --frozen-lockfile flag in CI environments to prevent lockfile updates
  • Leverage the --production flag to skip development dependencies in production deployments
  • Consider selective dependency resolution for problematic packages

These advanced techniques allow you to tailor Yarn to your specific project requirements, significantly enhancing your development workflow.

Performance Comparison: Yarn vs. npm on CentOS Stream 10

Understanding the performance differences between Yarn and npm on CentOS Stream 10 can help you make informed decisions about which package manager to use for your projects. This comparison focuses on key metrics that impact development efficiency.

Speed Benchmarks

Yarn consistently outperforms npm in installation speed due to its parallel download architecture. On CentOS Stream 10, fresh installs of large projects can be 1.5-2x faster with Yarn compared to npm. This performance gap is particularly noticeable in projects with numerous dependencies.

Memory Usage Comparison

Yarn typically uses more memory during initial installation but is more efficient in subsequent operations. On systems with limited resources, this initial memory spike might be a consideration, but the overall efficiency gains often outweigh this drawback.

Network Efficiency

Yarn’s caching mechanism significantly reduces bandwidth usage compared to npm. When reinstalling dependencies or working across multiple projects that share common packages, Yarn minimizes network requests by leveraging its local cache.

Disk Space Considerations

Yarn’s comprehensive caching approach may require more disk space than npm, particularly on systems where many different packages are used. However, this trade-off results in faster installations and better offline capabilities.

Real-world Performance Scenarios

In typical development scenarios on CentOS Stream 10:

  • For large monorepos with shared dependencies, Yarn shows 30-40% better performance
  • For continuous integration environments, Yarn’s deterministic installations reduce build time variability
  • For environments with intermittent connectivity, Yarn’s offline capabilities provide significant workflow improvements

These performance advantages make Yarn particularly well-suited for enterprise environments running CentOS Stream 10, where development speed and reliability are critical factors.

Troubleshooting Common Installation Issues

Even with careful planning, you might encounter issues when installing or using Yarn on CentOS Stream 10. This section addresses common problems and their solutions.

Permission-related Errors

If you encounter permission errors during installation, such as “EACCES: permission denied,” you have several options:

# Option 1: Use sudo (for global installations)
sudo npm install -g yarn

# Option 2: Change npm's default directory
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'

Remember to add the new npm directory to your PATH by adding the following line to your .bashrc:

export PATH=~/.npm-global/bin:$PATH

Then reload your profile with source ~/.bashrc.

Network Connectivity Problems

If Yarn can’t download packages due to network issues:

  1. Check your internet connection
  2. Verify proxy settings if applicable:
    yarn config set proxy http://your-proxy-server:port
    yarn config set https-proxy http://your-proxy-server:port
  3. Try using Yarn’s offline mode if packages are already cached:
    yarn --offline

Repository Access Issues

If you can’t access the Yarn repository:

  1. Verify the repository was added correctly:
    cat /etc/yum.repos.d/yarn.repo
  2. Check for repository GPG key issues:
    sudo rpm --import https://dl.yarnpkg.com/rpm/pubkey.gpg
  3. If problems persist, try a different installation method.

Dependency Conflicts

When facing package conflicts:

  1. Check for version incompatibilities in your package.json
  2. Use resolutions to force specific package versions:
    {
      "resolutions": {
        "conflicting-dependency": "1.2.3"
      }
    }
  3. Consider using yarn why [package-name] to understand dependency relationships

Version Incompatibilities

If you encounter the “No such file or directory: ‘install'” error:

  1. This often indicates a conflict with the system’s cmdtest package
  2. Remove any conflicting installations:
    sudo dnf remove cmdtest
    sudo dnf remove yarn
  3. Reinstall Yarn using one of the methods described earlier.

Path and Environment Variable Problems

If Yarn commands aren’t recognized after installation:

  1. Verify Yarn is in your PATH:
    echo $PATH | grep yarn
  2. Manually add Yarn to your PATH if necessary:
    export PATH="$PATH:`yarn global bin`"
  3. Make the change permanent by adding it to your .bashrc file

Updating Yarn

Keeping Yarn updated ensures you have access to the latest features, performance improvements, and security patches. The update process varies depending on how you initially installed Yarn.

Checking Current Version

Before updating, check your current Yarn version:

yarn --version

This helps you confirm that the update was successful afterward.

Different Update Methods

For npm installations:

sudo npm update -g yarn

For repository installations:

sudo dnf update yarn

For script installations:

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

Each method updates Yarn while preserving your configurations and caches.

Update Best Practices

Before updating in production environments:

  1. Read the release notes for breaking changes
  2. Test the update in a development environment first
  3. Back up your global Yarn configuration
  4. Consider updating one project at a time to identify any issues

These precautions help ensure a smooth transition to newer Yarn versions.

Handling Breaking Changes

When major Yarn updates introduce breaking changes:

  1. Review the migration guide in the official documentation
  2. Update your workflows and scripts if necessary
  3. Test thoroughly before deploying to production

Taking these steps minimizes disruption during version transitions.

Downgrading if Necessary

If an update causes problems, you can downgrade to a previous version:

# For npm installations
sudo npm install -g yarn@[version]

# For repository installations (if the version is available)
sudo dnf downgrade yarn-[version]

# For script installations
curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version [version]

Uninstalling Yarn

If you need to remove Yarn from your CentOS Stream 10 system, follow these steps based on your original installation method.

Removing via NPM

If you installed Yarn using npm:

sudo npm uninstall -g yarn

This command removes the global Yarn installation managed by npm.

Uninstalling via Package Manager

If you installed Yarn using dnf and the official repository:

sudo dnf remove yarn

This removes the Yarn package while preserving its configuration files.

Cleaning up Configuration Files

To completely remove all Yarn-related files:

rm -rf ~/.yarn
rm -rf ~/.yarnrc
rm -rf ~/.config/yarn

These commands delete Yarn’s cache, configuration, and global packages.

Removing Repositories

If you added the Yarn repository to your system:

sudo rm /etc/yum.repos.d/yarn.repo

This prevents future attempts to install packages from the Yarn repository.

Complete System Cleanup

For a thorough removal of all Yarn components:

sudo dnf remove yarn
rm -rf ~/.yarn
rm -rf ~/.config/yarn
rm -rf ~/.yarnrc
sudo rm /etc/yum.repos.d/yarn.repo

After running these commands, Yarn will be completely removed from your system.

Best Practices for Yarn on CentOS Stream 10

Implementing best practices for Yarn on CentOS Stream 10 ensures optimal performance, security, and maintainability for your JavaScript projects.

Security Considerations

To enhance the security of your Yarn installations:

  • Regularly update Yarn to the latest version to benefit from security patches
  • Use checksums to verify package integrity:
    yarn install --check-files
  • Consider using Yarn’s built-in security features to audit dependencies:
    yarn audit
  • Be cautious when adding third-party repositories to your system

Following these security measures helps protect your projects from potential vulnerabilities.

Performance Optimization

Maximize Yarn’s performance on CentOS Stream 10:

  • Use the --frozen-lockfile flag in production environments to skip lockfile generation
  • Leverage Yarn’s offline capabilities when appropriate
  • Consider using --production flag to skip development dependencies in production
  • Optimize your global cache for frequently used packages:
    yarn cache clean
    yarn cache dir

These optimizations can significantly reduce installation times, especially in CI/CD pipelines.

Integration with CI/CD Pipelines

For seamless integration with continuous integration systems:

  • Cache Yarn’s global cache between pipeline runs
  • Use --frozen-lockfile to ensure consistent installations
  • Include the yarn.lock file in your version control system
  • Consider using containerized environments with pre-installed Yarn for faster builds

These practices improve build consistency and reduce pipeline execution times.

Working with Containerized Environments

When using Yarn within Docker containers on CentOS Stream 10:

  • Include Yarn installation in your Dockerfile rather than relying on volume mounts
  • Consider multi-stage builds to minimize container size
  • Cache node_modules intelligently to speed up builds
  • Use yarn.lock to ensure consistent dependency resolution

Properly configured containerized environments provide consistent development and deployment experiences.

Enterprise Deployment Strategies

For enterprise-scale deployments:

  • Consider setting up a private npm registry with Verdaccio or Artifactory
  • Implement strict version locking policies
  • Establish team standards for dependency management
  • Create organizational-level Yarn configurations for consistency across projects

These strategies help large teams maintain consistent development environments while ensuring security and performance.

Congratulations! You have successfully installed Yarn. Thanks for using this tutorial for installing the Yarn on CentOS Stream 10 system. For additional help or useful information, we recommend you check the official Yarn website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button