How to easily upgrade npm packages
TLDR: How to update npm packages?
The simplest way is to install
npm-check-updates
, runnpx ncu
, followed bynpx ncu -u
to update the package.json followed bynpm install
to update packages in package.lock and node_modules.
Option 1: Classic npm approach
npm comes with the tools to upgrade your packages out of the box. When running npm outdated
you can get a list of packages that have available updates:
We can update individual packages by running npm update {package-name}
. Let's try it for the last package on the list:
npm update sass
Now if we run npm outdated
again we can (as seen in the image below) that the package was indeed updated. One thing to note is that while package.lock
was updated package.json
remains untouched.
Now we could do the same for all the packages and if you have a production-critical application, you probably want to pay close attention to the packages that you upgrade and the implications that an upgrade could have.
Option 2: npm-check-updates approach
Another option, that I find slightly more convenient, especially for more low-risk projects is using the npm-check-updates
package. To install it simply run:
npm install -g npm-check-updates
After it's installed we can check for updates by running:
npx ncu
Similar to npm outdated
this gives us a list of all available updates:
In order to update one single package we can run:
npx ncu -uf sass
followed by:
npm install
Now if we run npx ncu
again we see the sass
package was updated:
What is nice about the npm-check-updates package is that we can also update all of the packages if we choose so by running:
npx ncu -u
followed again by
npm install
Now if we run npx ncu
again we get:
Now both package.json
and package.lock
were updated, so this makes it clearer what version of the packages we have without the need to look into the package.lock
file.
Conclusion
If you want to easily upgrade all your packages you can use the npm-check-updates
npm package with the commands shown above, otherwise, you can also use npm's built-in commands npm outdated
and npm update
.
References: