npm vs pnpm vs Yarn: Which Should You Use?

A JavaScript package manager does one job: it takes the dependency list in your package.json, downloads the right versions, and wires them into your project so Node can load them. npm, pnpm, and Yarn all do that job. They differ in how they store the files, how fast they install, how strict they are about which code your files can reach, and how they handle install scripts. Those differences decide whether your CI stays fast, your disk stays small, and your builds stay reproducible.

Teams argue about this choice for years, and the argument usually misses the point. The question is not which tool is best in general. The question is which trade-off fits your repo. A solo developer with a small side project needs a different answer than a team running a monorepo with forty packages. This guide lays out the mechanics, the numbers, and the security trade-offs.

What a JavaScript Package Manager Actually Does

A package manager reads package.json, resolves every dependency to an exact version, records those versions in a lockfile, downloads the packages from a registry, and places them where Node can find them. The lockfile is the part most developers ignore until it saves them. It pins the full dependency tree, so a fresh install on a teammate laptop or a CI runner produces the same tree you tested locally. Without a committed lockfile, two installs of the same project can pull different versions of a transitive dependency, and the bug that appears only in CI becomes a long afternoon.

Each manager keeps its own lockfile format. npm writes package-lock.json. pnpm writes pnpm-lock.yaml. Yarn writes yarn.lock. The formats are not interchangeable, and switching managers means generating a new lockfile.

Installation has two phases: resolving the tree and downloading tarballs, then linking those files into your project. npm copies files into node_modules. pnpm stores one copy of each package version in a global store on your disk and hard-links it into each project, so ten projects using the same version of a package share one copy on disk. Yarn with Plug-n-Play skips node_modules entirely and generates a single .pnp.cjs loader file that tells Node where each package lives.

The same debate exists in other ecosystems. If you manage Python dependencies, the same trade-offs between speed, disk use, and strictness show up in our comparison of uv vs pip vs Poetry, and the reasoning there transfers well to JavaScript tooling.

How npm, pnpm, and Yarn Build node_modules Differently

npm uses a hoisted layout by default. It flattens dependencies into a single node_modules tree, lifting shared packages to the top level so they are installed once. The install-strategy setting controls this, and hoisted is the default. Hoisting is convenient, and it creates a specific bug class: phantom dependencies. Your code can import a package that is not listed in your package.json, because that package happens to sit in node_modules as a dependency of something else.

pnpm takes the opposite approach. It builds a strict tree with a virtual store inside node_modules, and each package can only reach the dependencies listed in its own package.json. Packages are hard-linked from a global content-addressable store, so installing the same package in five projects costs the disk space once. The pnpm FAQ explains the math plainly: if a package occupies 1MB, five projects using it still occupy 1MB in total, not 5MB. On Windows machines without symlink rights, pnpm falls back to junctions instead of symlinks. The strict layout kills phantom dependencies at the source, and that alone justifies the switch for many teams.

Yarn offers two modes. Classic Yarn behaves much like npm, with a hoisted node_modules tree. Yarn with Plug-n-Play, or PnP, removes node_modules and emits a single .pnp.cjs loader. Node reads that file and resolves imports from a central cache. The cost is compatibility. Some tools expect node_modules to exist, and they need a PnP-aware resolver or a compatibility patch before they work. Editor integrations, ESLint, and TypeScript all need a small setup step with PnP, and that setup step is where teams lose an afternoon.

Disk use follows directly from these designs. npm copies everything per project. pnpm shares one copy across projects. Yarn PnP keeps one cache and no per-project tree. On a laptop with twenty JavaScript projects, the difference shows up in gigabytes, and it shows up again in Docker images when the whole dependency tree ships inside the image. The same size discipline applies to Python images, as our guide to Docker multi-stage builds shows for a different stack.

Speed, Disk Use, and Workspaces Side by Side

The table below compares the three managers on the criteria that matter in daily use. No single row decides the choice. Read the rows that match your pain: disk pressure, CI time, monorepo size, or strictness.

CriterionnpmpnpmYarn
Lockfilepackage-lock.jsonpnpm-lock.yamlyarn.lock
Install layoutHoisted node_modulesStrict tree, hard links from global storeHoisted tree, or PnP with no node_modules
Disk useOne copy per projectOne copy shared across projectsShared cache, small per-project footprint with PnP
Monorepo workspacesSupportedSupported, with filtered commandsSupported, mature workspace tooling
Phantom dependenciesPossibleBlocked by strict layoutBlocked with PnP, possible in classic mode
Install script policyBlocked by default in npm 12Approval flow for scriptsConstraints and per-package settings
Offline supportCache-basedGlobal store and offline mirrorOffline mirror support
Manager pinningCorepack, packageManager fieldCorepack, packageManager fieldCorepack, packageManager field
Learning curveLow, ships with NodeLow, mostly npm-compatible commandsMedium with PnP, low in classic mode

Workspaces deserve a closer look because monorepos amplify every difference. All three managers support workspaces, so the choice is about ergonomics rather than capability. pnpm filters commands per workspace package with a short flag, and its strict layout keeps cross-package imports honest. Yarn workspaces have the longest track record, and many large monorepos still run on them. npm workspaces cover the basics well, and teams already on npm rarely gain enough from switching to justify the migration cost on workspaces alone.

Commands differ in small ways that add up. Adding a dependency, removing one, running a script, and doing a frozen install in CI each have a direct equivalent across the three tools. Commands transfer in a day. The lockfile does not, and that is the real switching cost.

Reading the Benchmark Numbers Without Getting Fooled

Speed claims dominate every comparison article, so read them with care. The most cited numbers come from the pnpm benchmark suite, published by the pnpm project itself. On its own test rig, with data fetched November 22, 2026, a clean install of the alotta-files project took npm 43.1 seconds and pnpm 12 only 4.03 seconds. Across all six install scenarios in the suite, npm totaled 1 minute 8 seconds against 9.14 seconds for pnpm 12, and the variant using the pnpm runner finished in 6.09 seconds. A weighted mix meant to mirror typical usage landed at 2 minutes 16 seconds for npm and 18.2 seconds for pnpm 12.

The pnpm homepage states the same result more aggressively: up to 69 times faster than npm, and 8.2 times faster in total across all six scenarios, quoted as 10.8 seconds against 1 minute 28 seconds for npm. Those two totals disagree with the benchmark page, because they come from different scenario sets and versions. I checked both pages on the day this article was written, and the numbers above match what they publish today.

Three caveats matter more than the headline multiplier. First, the benchmark suite is maintained by the pnpm project, so treat it as vendor data rather than neutral measurement. I could not find an independent head-to-head benchmark, and the Yarn performance page returns a 404. Second, warm-cache scenarios inflate multipliers. A second install with everything cached tells you little about a cold CI runner pulling fresh tarballs. Third, cold CI installs are the only numbers that matter for a pipeline. If your CI uses a warm cache, the gap shrinks. A warm cache in CI changes the math for every manager, and our guide to GitHub Actions cache shows how to set one up before you blame the package manager.

Laptop screen showing JavaScript code in an editor with a terminal window open

Disk speed, network speed, and registry latency also shape real install times. A slow registry connection hurts npm more than pnpm in a cold install, because npm downloads and copies more data. Measure your own repo on your own runner before quoting a multiplier to your team. One timed run of a clean install on each manager, on the same machine, beats any benchmark page.

Lockfiles and Install Scripts: Where Security Lives

The lockfile is the most valuable file in your repository for security, not just for reproducibility. In September 2025, a self-replicating worm known as Shai-Hulud compromised over 500 packages in the npm ecosystem, according to a CISA alert dated September 23, 2025. CISA told defenders to check for package-lock.json or yarn.lock files as part of the response. The lockfile tells you exactly which versions were installed, which makes it possible to find out whether a compromised version ever reached your machines.

Install scripts are the second half of the problem. A lifecycle script runs code during installation, before you have reviewed anything. That code runs with your user permissions, and a malicious script can read environment variables, including tokens and keys. npm 12 blocks dependency install scripts by default. Install commands skip lifecycle scripts for any dependency without a matching entry in the allowScripts list, and the npm approve-scripts command manages that list. Confirm what npm 11 LTS does before assuming the same behavior, because the default changed with npm 12.

pnpm handles the same risk with an approval flow. Scripts do not run until you approve them, and the approval is recorded so later installs stay consistent. Yarn uses constraints and per-package settings to control which scripts may run. The mechanisms differ, and the principle is the same: no package should run code on your machine during install unless you said so.

Three habits cover most of the risk. Commit the lockfile and review its diff in every pull request, because a lockfile change is a dependency change. Keep install scripts blocked or approved explicitly. Audit new dependencies before adding them, and remove packages you no longer use. These habits matter even more for AI-generated code, so review them before you ship a vibe-coded app with a dependency list nobody has read.

Switching Managers Without Breaking Your CI

Switching is a small project, not a single command. Start by pinning the manager itself. Corepack ships with Node and reads the packageManager field in package.json. It accepts yarn, npm, and pnpm as values, and it supports an optional hash that the Node docs strongly recommend as a security practice. Pinning the manager means every laptop and every CI runner uses the same binary, and nobody silently installs with a different tool. Enable Corepack, set the field, and commit it.

Next, generate the new lockfile. Delete the old lockfile and the node_modules folder, then run a fresh install with the new manager. Review the new lockfile diff before merging. A lockfile diff that adds or removes unexpected packages is a signal to stop and read it, not to wave it through.

Builds break in three predictable places. First, code that imports a phantom dependency fails under pnpm strictness or Yarn PnP, because the package was never declared. Fix the imports by adding the missing dependency to package.json. Second, tools that assume node_modules exists need a PnP-aware resolver, so check your editor, linter, and bundler setup before switching to PnP. Third, CI scripts that call npm ci need the equivalent command in the new manager: a frozen install that fails when the lockfile and package.json disagree. npm ci itself is that command for npm, and it exits with an error on mismatch while removing any existing node_modules first.

Change the CI config in the same pull request as the lockfile. Update the install step, the cache key, and the frozen-install command together, so a reviewer sees the full change in one place. Run the pipeline twice before merging, once warm and once cold. If the cold run passes and the timings look right, merge and tell the team which command replaces npm ci in their daily workflow.

FAQ: npm vs pnpm vs Yarn

Should I switch from npm to pnpm? Switch if disk use or install time hurts you, or if phantom dependencies have bitten your team. Stay on npm if your setup works and nobody on the team feels the pain. The default manager ships with Node, needs no setup, and now blocks install scripts by default in npm 12.

Does Yarn PnP work with every tool? Not out of the box. Most mainstream tools support PnP now, but each one needs a small setup step: a resolver patch, a plugin, or an editor SDK. Budget an afternoon for the first repo, and check your specific toolchain before committing. Classic Yarn mode avoids this cost entirely and behaves like npm.

Can I use different managers in different projects? Yes, and most developers already do. Pin the manager per project with the packageManager field, and each repo stays consistent on its own. Mixing managers inside one project is where trouble starts, so pick one per repo and enforce it in CI.

Take Action: Pick One and Pin It

The verdict is short. Stay on npm when you want zero setup and the newest default script protection. Switch to pnpm for large repos, monorepos, and disk-bound CI, where its strict layout and shared store pay off every day. Choose Yarn PnP only for greenfield repos where the team accepts a small tooling setup cost in exchange for no node_modules at all. Each choice is defensible, and each one fails when it is not pinned.

Pick one this week and pin it with the packageManager field. Generate the lockfile, update the CI config, and run the pipeline cold once. Tell us in the comments which manager your team runs and what pushed you to it.

Irfan is a Creative Tech Strategist and the founder of Grafisify. He spends his days testing the latest AI design tools and breaking down complex tech into actionable guides for creators. When he’s not writing, he’s experimenting with generative art or optimizing digital workflows.

Leave a Reply

Your email address will not be published. Required fields are marked *

You might also like
OAuth vs OIDC vs SAML: Which Should You Use?

OAuth vs OIDC vs SAML: Which Should You Use?

Passkeys vs Passwords: Which Is More Secure?

Passkeys vs Passwords: Which Is More Secure?

SPF, DKIM, and DMARC: A Practical Setup Guide

SPF, DKIM, and DMARC: A Practical Setup Guide

How to Build a Home Server with a Raspberry Pi

How to Build a Home Server with a Raspberry Pi

Nginx Reverse Proxy for Docker: Practical Setup Guide

Nginx Reverse Proxy for Docker: Practical Setup Guide

How to Speed Up a Slow WordPress Site

How to Speed Up a Slow WordPress Site