DEV Community

Lorenzo Rivosecchi
Lorenzo Rivosecchi

Posted on

How to pin Node.js and PNPM versions in your project

When you start working on a new project, it can be hard to figure out how to use the correct versions of Node and PNPM. Today I finally found a strategy that makes sense.

Install node and corepack

I recommend installing node and corepack with brew:

brew install node corepack
Enter fullscreen mode Exit fullscreen mode

The node version will be the latest, because we will let pnpm manage it for us.

Install pnpm with corepack

Corepack allows us to pin a specific package manager and version to our package.json, so open your project folder at the package.json level and run this command:

corepack enable
corepack use pnpm@9
Enter fullscreen mode Exit fullscreen mode

This will add the following line to your package.json

+  "packageManager": "pnpm@9.15.9+sha512.68046141893c66fad01c079231128e9afb89ef87e2691d69e4d40eee228988295fd4682181bae55b58418c3a253bde65a505ec7c5f9403ece5cc3cd37dcf2531"
 }
Enter fullscreen mode Exit fullscreen mode

Now, when someone wants to contribute you can tell them to run

corepack install
Enter fullscreen mode Exit fullscreen mode

You can verify your pnpm version with:

pnpm -v
Enter fullscreen mode Exit fullscreen mode

Pinning Node.js version

Now that you have installed pnpm you can use it to run your scripts with a specific Node.js version.

Add this line to your package.json:

+  "pnpm": {
+    "executionEnv": {
+      "nodeVersion": "20.19.5"
+    },
   }
 }
Enter fullscreen mode Exit fullscreen mode

Now, when you run the next pnpm run command, the specified Node.js version will be downloaded and used instead of the one installed via homebrew.

echo "local: $(pnpm exec node -v)"
echo "global: $(node -v)"
Enter fullscreen mode Exit fullscreen mode

Switching Node.js version globally

PNPM can be used to manage your node.js version outside of your project as well. Here is how you would do it:

pnpm env --global use 20.19.5
Enter fullscreen mode Exit fullscreen mode

If installing node.js with homebrew, to install pnpm through corepack with the intent of using it to install node.js again is too weird, I understand.

As an alternative to this madness, you could install [nvm] or [volta] to manage global node versions, and do the same things to

  • Enable corepack
  • Use it to install and pin pnpm version
  • Use pnpm to pin local node.js version*

*Why is this necessary when i can pin the version with .nvmrc?

The reason is that with .nvmrc you need to remember running nvm use, while the pnpm.executionEnv.nodeVersion will always use the correct node version when calling a script.

Top comments (0)