Avoid package resolution errors by setting a package manager in the package.json
Developers working on Node projects have likely encountered errors related to package resolution at some point in their careers. It's so common that removing the node_modules
directory and reinstalling all of the project dependencies is one of the first things folks attempt in an effort to resolve these.
From my experience, these errors tend to be a result of one of the following:
- Misconfiguration of the project (
tsconfig.json
,vite build
settings, etc.); - ESM/CommonJS dependencies clashing within a project and its build settings;
- Projects were built by the authors with the expectation that a specific package manager would be used to install and maintain the project dependencies.
Today I want to focus on that last point - the expectations of which package manager would be used in the project.
For the most part npm
, yarn
, and pnpm
tend to work similarly but there are some differences.
As an example, pnpm
doesn't install directory dependencies by default like npm
does. If you're used to using npm
and expecting that those dependencies are installed by default, you'll likely be puzzled as to why the project isn't working out-of-the-box if pnpm install
was used instead.
Guidance as to which package manager to use from the authors of the project tends to be communicated subtly. Commands in an install
script in the package.json
, the presence of a certain type of lockfile, or using a particular package manager in commands to be copy-and-pasted in a project's README.md
are a few examples.
Rather than rely on chance that other developers will notice these hints and use the right package manager in our projects, let's be explicit about what we expect!
Introducing the packageManager
property
The packageManager
property in the package.json
can be used to explicitly tell developers working on the project which one they are expected to use.
By setting this in our projects, we can save developers valuable time when they're first getting started, or are looking to just get it running.
This is still an experimental property within Node but is worth paying attention to if errors related to the use of different package managers is something you and your teams run into more often than you'd like.
Like what you've read?
Subscribe to receive the latest updates in your inbox.