DEV Community

Cover image for Who manages the package managers?
Jake Patterson
Jake Patterson

Posted on • Edited on • Originally published at jake8n.com

Who manages the package managers?

The JavaScript ecosystem is notorious for moving quickly. Just a few years ago Yarn (now Yarn Classic) was ubiquitous. Since then, 3 major yarn versions have been released and new competitors have entered the market. While upgrade paths can be straight forward—with pnpm even providing pnpm upgrade—the problem of managing package managers arises.

Consider an organisation with hundreds of JavaScript repositiories. Some have long been abandoned and others have an active development team keen to use the best-in-class tooling. Maybe at a glance it is obvious which flavour of package manager a repository depends on; we may see a package-lock.json or yarn.lock file. However, further inspection is needed to determine which version of NPM or Yarn created those. It is too easy for a developer to end up recreating a lock file after running the wrong command. Not a great experience!

A better approach is to use a combination of the following tools. Firstly, fnm (Fast Node Manager) is a well established Node version manager. After setting up your shell environment, navigating to a project folder is all that is required to detect and switch to the correct Node version, provided a .node-version file exists. We can take this a step further by adding packageManager to our package.json:

+ "packageManager": "pnpm@8.14.3"
Enter fullscreen mode Exit fullscreen mode

On its own that isn't going to do much. A developer would still need to open package.json to find the correct package manager to download. We can automate that with Corepack. Corepack is an experimental feature of Node that looks for the packageManager field and silently downloads the version when running scripts. It also throws an error if the wrong package manager is used in the scope of the project. It is an opt-in feature though, so corepack enable must be run after Node is installed. Alternatively, fnm can be configured to do that automatically:

- eval "$(fnm env --use-on-cd)"
+ eval "$(fnm env --use-on-cd --corepack-enabled)"
Enter fullscreen mode Exit fullscreen mode

Now, running any package manager command comes with a guarantee; with the above configuration, pnpm -v always resolves to 8.14.3 and yarn -v errors. Note that package managers previously installed globally should be uninstalled first. Without doing that, we won't see the wonderful error:

Usage Error: This project is configured to use pnpm

Top comments (0)