How to update your npm packages

How to update your npm packages

To update your npm packages and ensure that the updated versions are reflected in your package.json, you can follow these steps:

1. Check for Outdated Packages

First, identify which packages are outdated:

npm outdated

This command will list all the outdated packages in your project, showing the current version, the wanted version (the latest version according to your package.json semver rules), and the latest available version.

2. Update Packages

Update a Single Package:

To update a specific package and save the updated version to your package.json, use:

npm install <package-name>@latest --save

For example:

npm install express@latest --save

This will install the latest version of express and update your package.json accordingly.

Update All Packages:

To update all the packages listed in your package.json to their latest versions and save those versions back to package.json, run:

npm update --save

This command updates the packages to the highest version that still respects the semver (semantic versioning) range specified in your package.json.

Upgrade All Packages to the Latest Major Version:

If you want to upgrade all your dependencies to their latest versions, including major versions that might include breaking changes, you can use:

npx npm-check-updates -u
npm install
  • npx npm-check-updates -u: This command will update the version numbers in your package.json to the latest versions available on npm, even if they include major version changes.
  • npm install: This will install all the packages according to the new version numbers in your package.json.

Note: Be cautious with this approach as major version changes can introduce breaking changes.

3. Verify and Test

After updating, it's important to test your application to ensure that everything works correctly with the new versions. Run your test suite and any other relevant checks to verify that the update did not introduce any issues.

4. Lock Package Versions (Optional)

To prevent unintentional updates in the future, you can lock your dependencies to specific versions by using an exact version number in package.json, like:

"dependencies": {
  "express": "4.17.1"
}

Alternatively, you can use npm shrinkwrap or a lock file (package-lock.json) to ensure that the exact same versions of dependencies are installed each time.

Summary

  • Use npm outdated to check for outdated packages.
  • Update a single package with npm install <package-name>@latest --save.
  • Update all packages with npm update --save.
  • Upgrade all packages to the latest versions with npx npm-check-updates -u followed by npm install.
  • Always test your application after updates to ensure compatibility with the new package versions.

More to read