Skip to main content

JavaScript Package Managers

Introduction

When building modern JavaScript applications, you rarely write all the code from scratch. Instead, you leverage existing code written by other developers in the form of packages or libraries. JavaScript package managers are tools that help you install, update, configure, and manage these external dependencies in your projects.

In this tutorial, you'll learn:

  • What package managers are and why they're essential
  • How to use popular package managers like npm and Yarn
  • How to manage project dependencies
  • Best practices for working with package managers

What is a Package Manager?

A JavaScript package manager is a tool that automates the process of installing, upgrading, configuring, and removing JavaScript packages from your project. These packages are reusable code modules that provide specific functionality.

Package managers help solve several common problems:

  1. Dependency Management: Tracking which packages your project needs
  2. Version Control: Managing which versions of packages work with your code
  3. Dependency Resolution: Automatically installing dependencies of dependencies
  4. Script Running: Executing predefined commands for development tasks

npm (Node Package Manager)

npm is the default package manager for Node.js and is installed automatically when you install Node.js.

Key Features of npm:

  • The world's largest software registry with over 1.3 million packages
  • Command-line interface for package installation and management
  • Support for semantic versioning
  • Built-in security features

Yarn

Yarn was developed by Facebook as an alternative to npm, focusing on speed, reliability, and security improvements.

Key Features of Yarn:

  • Faster installation due to parallel operations and caching
  • Deterministic installations across environments
  • Enhanced security features
  • Offline mode capabilities

pnpm

pnpm is a newer package manager that focuses on disk space efficiency by using a single content-addressable storage for all packages.

Key Features of pnpm:

  • Saves disk space by using hard links and symlinks
  • Faster installations
  • Strict dependency management
  • Compatibility with npm workflows

Getting Started with npm

Installing npm

npm comes bundled with Node.js, so you just need to install Node.js:

  1. Visit Node.js website
  2. Download and install the LTS (Long Term Support) version
  3. Verify installation with:
bash
node -v
npm -v

npm Basics

Initializing a Project

To start a new project with npm:

bash
mkdir my-project
cd my-project
npm init

This creates a package.json file that tracks your project's dependencies and metadata. For a quicker setup with default values, use:

bash
npm init -y

Installing Packages

To install a package:

bash
npm install lodash

This will:

  1. Download the lodash package
  2. Save it in the node_modules directory
  3. Update your package.json to include it as a dependency

Types of Dependencies

You can specify different types of dependencies:

bash
# Regular dependency (used in production)
npm install lodash

# Development dependency (not used in production)
npm install --save-dev jest

# Global installation (available system-wide)
npm install -g typescript

package.json Example

After installing some packages, your package.json might look like this:

json
{
"name": "my-project",
"version": "1.0.0",
"description": "My awesome JavaScript project",
"main": "index.js",
"scripts": {
"test": "jest",
"start": "node index.js"
},
"dependencies": {
"lodash": "^4.17.21",
"axios": "^0.24.0"
},
"devDependencies": {
"jest": "^27.4.5",
"eslint": "^8.5.0"
}
}

Running Scripts

npm allows you to define and run scripts in your package.json:

bash
# Run the "test" script
npm test

# Run the "start" script
npm start

# Run a custom script
npm run build

Working with Yarn

Installing Yarn

bash
npm install -g yarn

Verify installation:

bash
yarn --version

Yarn Basics

Initializing a Project

bash
mkdir yarn-project
cd yarn-project
yarn init

For default initialization:

bash
yarn init -y

Installing Packages

bash
# Add a dependency
yarn add lodash

# Add a dev dependency
yarn add --dev jest

# Add a global dependency
yarn global add typescript

yarn.lock File

Yarn creates a yarn.lock file that locks down the versions of all dependencies, ensuring consistent installations across environments.

Managing Project Dependencies

Understanding Semantic Versioning

Both npm and Yarn use semantic versioning (semver) to manage package versions:

  • Major version (1.x.x): May include breaking changes
  • Minor version (x.2.x): Adds functionality without breaking changes
  • Patch version (x.x.3): Bug fixes without adding functionality

In package.json, version ranges can be specified using special syntax:

json
{
"dependencies": {
"exact-version": "1.2.3",
"compatible-updates": "^1.2.3", // 1.x.x (any minor or patch)
"minor-updates": "~1.2.3", // 1.2.x (only patch)
"any-version": "*"
}
}

Updating Packages

With npm:

bash
# Check for outdated packages
npm outdated

# Update packages according to semver rules in package.json
npm update

# Update to the latest version (potentially breaking)
npm install lodash@latest

With Yarn:

bash
# Check for outdated packages
yarn outdated

# Update packages
yarn upgrade

# Update a specific package to latest
yarn upgrade lodash --latest

Removing Packages

With npm:

bash
npm uninstall lodash

With Yarn:

bash
yarn remove lodash

Package-lock Files and Security

package-lock.json (npm) and yarn.lock (Yarn)

Both npm and Yarn create lock files that:

  1. Record the exact versions of installed packages
  2. Ensure consistent installations across environments
  3. Speed up installations by providing a snapshot of dependencies

Always commit these files to your version control system.

Security Auditing

Both package managers provide tools to check for vulnerabilities:

With npm:

bash
npm audit
npm audit fix

With Yarn:

bash
yarn audit

Practical Example: Setting Up a React Project

Let's see package managers in action by setting up a simple React project:

Using npm

bash
# Create a new React project
npx create-react-app my-react-app

# Navigate to project directory
cd my-react-app

# Install additional packages
npm install axios styled-components

# Start the development server
npm start

Using Yarn

bash
# Create a new React project
yarn create react-app my-react-app

# Navigate to project directory
cd my-react-app

# Install additional packages
yarn add axios styled-components

# Start the development server
yarn start

Best Practices

  1. Always use lock files: Commit package-lock.json or yarn.lock to ensure consistent installations.

  2. Be specific about versions: Use caret (^) for minor and patch updates, tilde (~) for patch updates only.

  3. Regularly update dependencies: Keep dependencies updated, but test thoroughly after updates.

  4. Audit regularly: Run security audits to identify and fix vulnerabilities.

  5. Clean installations: When having issues, try a clean install:

    bash
    # npm
    rm -rf node_modules
    npm ci

    # yarn
    rm -rf node_modules
    yarn install --frozen-lockfile
  6. Use scripts: Define common tasks in your package.json scripts section.

Summary

JavaScript package managers like npm and Yarn are essential tools for modern web development, allowing you to:

  • Manage project dependencies efficiently
  • Install and update third-party packages
  • Ensure consistent environments across development and production
  • Run scripts for common development tasks
  • Check and fix security vulnerabilities

Whether you choose npm, Yarn, or pnpm, understanding how to use package managers effectively will make your JavaScript development experience much smoother and more productive.

Additional Resources

Exercises

  1. Initialize a new JavaScript project using npm and install three packages: lodash, axios, and moment.

  2. Create a simple Node.js script that uses one of the installed packages.

  3. Convert your npm project to use Yarn instead. What files change?

  4. Create a custom npm script that runs multiple commands in sequence.

  5. Try installing a specific older version of a package, then update it to the latest version.



If you spot any mistakes on this website, please let me know at feedback@compilenrun.com. I’d greatly appreciate your feedback! :)