Back to list
ReactpnpmCorepackNode.jsSetup

[React][Setup] Enable pnpm with Corepack and Enforce It

Activate pnpm via Corepack, then lock the project to pnpm only so accidental npm or yarn installs cannot break your lockfile.

1. Environment

  • OS: Windows 11 / macOS
  • Toolchain: Node.js, NVM, Corepack, pnpm
  • Terminal: PowerShell (Windows) / zsh (macOS)

2. Problem

When you install Node.js, the older package manager npm ships with the runtime by default.

  • You cannot fully remove npm and leave only pnpm on the machine.
  • Even if the team standard is pnpm, someone may habitually run npm install or yarn. That can scramble an optimized node_modules layout and the lockfile in seconds.

3. Cause

Why bother turning npm aside and standardizing on pnpm?

Disk efficiency (content-addressable store)

With npm, ten projects that all depend on the same library (for example React) often download that library ten times. pnpm keeps one copy in a global content-addressable store and links each project to it, so disk use stays much lower.

Faster installs

Because heavy packages are not re-downloaded for every project, pnpm install is often 2|–× faster than npm for the same dependency tree.

Blocking phantom dependencies

npm?’s loose hoisting can let you import packages you never declared. That may work locally and then fail in production. pnpm?’s stricter layout blocks those ghost imports at the source.

4. Solution

1) Prepare Node.js with NVM

Install an LTS Node.js version through NVM first (see the previous post).

2) Enable pnpm with Corepack

From Node.js v16.9+, Corepack is included to manage package managers. Use it to enable pnpm (Windows and macOS):

# Enable pnpm through Corepack
corepack enable pnpm

# Confirm pnpm is available
pnpm -v

3) Enforce pnpm in the project (safety net)

Open package.json in the project root and add a preinstall script that runs before any package install:

{
  "name": "my-awesome-project",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preinstall": "npx only-allow pnpm"
  }
}

If someone runs npm install or yarn install by mistake, the install stops with a clear error: this project allows pnpm only.

5. Summary

Common command mapping between npm and pnpm:

Task npm pnpm
Install all packages npm install pnpm install
Add a library npm install axios pnpm add axios
Start the dev server npm run dev pnpm dev
Build the project npm run build pnpm build

Related posts