Package Managers (npm, yarn)

Package managers simplify the process of installing, updating, and managing third-party libraries in JavaScript projects. The two most popular package managers are npm and Yarn.

Illustration of Package Managers
Illustration of Package Managers

💡 What is a Package Manager?

A tool that automates the installation, upgrading, configuration, and removal of software packages (libraries/modules) for your project.

Why Use Package Managers?

  • Automatically handle dependencies and their versions.
  • Maintain a manifest file (package.json) listing all dependencies.
  • Simplify sharing and collaboration across teams.
  • Enable easy scripts to run tasks like testing or building.

npm (Node Package Manager)

npm is the default package manager for Node.js. It comes bundled with Node.js installations.

  • npm init - creates a package.json file.
  • npm install <package> (or npm i <package>) - installs a package and adds it to dependencies.
  • npm install - installs all dependencies from package.json.
  • npm update - updates installed packages.
  • npm uninstall <package> - removes a package.

Yarn

Yarn is an alternative package manager developed by Facebook, designed to be fast and deterministic.

  • yarn init - creates a package.json file.
  • yarn add <package> - installs a package and adds it to dependencies.
  • yarn install - installs all dependencies listed in package.json.
  • yarn remove <package> - removes a package.
  • Uses yarn.lock file for consistent installs across machines.
npm vs Yarn: Common Commands
Actionnpm CommandYarn Command
Initialize projectnpm inityarn init
Install all dependenciesnpm installyarn install
Install a packagenpm install packageyarn add package
Remove a packagenpm uninstall packageyarn remove package
Update packagesnpm updateyarn upgrade

💡 Package Versioning

Both npm and Yarn respect semantic versioning defined in package.json. This helps control which package updates are allowed during installs or updates.

⚠️ Avoid Mixing npm and Yarn

Using both package managers interchangeably in the same project can corrupt the dependencies and lockfiles. Pick one and stick with it.

How Package Managers Work Under the Hood

  • Download the package from a public registry (like npm registry).
  • Install dependencies recursively.
  • Create or update the lockfile (package-lock.json for npm, yarn.lock for Yarn) to ensure consistent installs.

Summary

  • npm is the default and most widely used package manager for Node.js.
  • Yarn offers faster installs and deterministic dependency resolution.
  • Commands differ slightly but achieve similar results.
  • Always use one package manager per project to avoid conflicts.