Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing npm commands in favor of pnpm

I would like to switch to using PNPM over NPM for the usual reasons. Unfortunately cut and paste, or muscle memory takes over sometimes and I will accidentally use NPM to install a package in a project that is using already using PNPM. Things do not go well for that project anymore.

I am hoping to block or alias NPM commands in favor of PNMP.

Things I have tried:

  1. Only Allow - although promoted on the PNPM site, it does not seem to work, at least not work for individual imports which is the most common use case.

  2. Since my terminal is Oh My ZSH, I found code to add to ~/.zshrc to block npm if in a directory containing a PNPM lockfile.

NPM_PATH=$(which npm)
npm () {
  if [ -e PNPM-lock.yaml ]
  then
    echo "Please use PNPM with this project"
  elif [ -e yarn.lock ]
  then
    echo "Please use Yarn with this project"
  else
    $NPM_PATH "$@"
  fi
}

This seems to work for my purposes, but does anyone have any cleaner / less zsh-specific alternatives?

And in the case where it does happen, what is the recommended steps to recover a PNMP projected tainted by an NPM install?

like image 409
cycle4passion Avatar asked Nov 29 '25 19:11

cycle4passion


1 Answers

You've already mentioned the only-allow package.

NodeJS v16.9.0 and v14.19.0 support a new experimental packageManager field in the package.json file.

Type: <string>

{
  "packageManager": "<package manager name>@<version>"
}

The "packageManager" field defines which package manager is expected to be used when working on the current project. It can be set to any of the supported package managers, and will ensure that your teams use the exact same package manager versions without having to install anything else other than Node.js.

This field is currently experimental and needs to be opted-in; check the Corepack page for details about the procedure.

To recover a PNMP projected tainted by an NPM install, as long as you've specified your dependency versions as you'd really like them to work, you could just delete the node_modules folder and the package-lock.json file. But you could also take a look at PNPM's import subcommand

pnpm import generates a pnpm-lock.yaml from another package manager's lockfile [...]

like image 60
starball Avatar answered Dec 01 '25 11:12

starball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!