How to override your dependency's dependencies (Node.js)
- Published at
- Updated at
- Reading time
- 2min
npm released version 8
of their CLI client in December, and the minor version release looks unspectacular but includes a very helpful new feature - "overrides".
The JavaScript ecosystem has been on fire since Node.js and npm appeared. There's always a package for everything because folks have been YOLO-publishing whatever they please. It's a vibrant and enabling ecosystem feeling like the wild wild west. And of course, there are pros and cons to countless dependencies.
I love that I can "just install another package" but share the concerns about the increasing project complexity. Suppose your project relies on one dependency that depends on another one that again depends on another. In that case, countless things could go wrong, but the most critical one is when of your dependencies was hacked or does something malicious.
Read more about a recent occasion and the node-ipc
incident in March 2022.
"npm overrides" give you more control over what's installed in your dependency tree.
Let's say one of your dependencies (1st level) relies on another dependency that includes outdated other dependencies (2nd level). There hasn't been an easy way to control nested dependency versions down the node_modules
tree other than forking and fixing your first-level dependency.
your-project
|_ some-module @1.0.0
|_ another-module-which-should-be-updated @1.0.0
You can now specify an overrides
property in your package
to override and enforce nested dependency versions.
{
"overrides": {
"bar@2.0.0": {
"foo": "1.0.0"
}
}
}
Above the bar
package with the version 2
would be overriden by foo
.
Our friends at Snyk shared a snippet that describes how to override a package with a specific version range. Read the following package
configuration as:
- override every
node-ipc
package larger than9
but smaller than.2 .1 10
. - override every
node-ipc
package larger than10
..1 .0
{
"overrides": {
"node-ipc@>9.2.1 <10": "9.2.1",
"node-ipc@>10.1.0": "10.1.0"
}
}
The new overrides feature comes in handy to:
- patch a dependency with a known security issue
- replace an existing dependency with a fork
- make sure that the same package version is used everywhere.
It's such a welcome addition; thanks, npm! 🎉
Join 5.3k readers and learn something new every week with Web Weekly.