How do I override nested NPM dependency versions?

node.js, npm

Solution

As of npm v8.3 (released with Node.js 16), the correct way to deal with this is via the `overrides` section of your `package.json` file.

If you need to make specific changes to dependencies of your dependencies, for example replacing the version of a dependency with a known security issue, replacing an existing dependency with a fork, or making sure that the same version of a package is used everywhere, then you may add an override.

Overrides provide a way to replace a package in your dependency tree with another version, or another package entirely. These changes can be scoped as specific or as vague as desired.

To make sure the package foo is always installed as version 1.0.0 no matter what version your dependencies rely on:

{
  "overrides": {
    "foo": "1.0.0"
  }
}

There are a variety of other, more nuanced configurations allowing you to only override a package when it's a dependency of a particular package hierarchy. For more details, check out https://docs.npmjs.com/cli/v9/configuring-npm/package-json#overrides

Problem

I would like to use the `grunt-contrib-jasmine` NPM package. It has various dependencies. Part of the dependency graph looks like this: ``` ─┬ grunt-contrib-jasmine@0.4.1 │ ├─┬ grunt-lib-phantomjs@0.2.0 │ │ ├─┬ phantomjs@1.8.2-2 ``` Unfortunately, there's a bug in this version `phantomjs` which prevents it from installing correctly on Mac OS X. This is fixed in the latest version. How can I get `grunt-lib-phantomjs` to use a newer version of `phantomjs`? Some additional context: - `grunt-contrib-jasmine` explicitly requires version `"~0.2.0"` of `grunt-lib-phantomjs`, which explicitly requires version `"~1.8.1"` of `phantomjs`. - Adding `phantomjs` to my package's dependencies first has no effect; both versions are installed and `grunt-contrib-jasmine` still uses the older versions (see: When installing a package with NPM, can you tell it to use a different version of one of its dependencies?).

Original source

Related problems