To update all dependencies in your package.json to their latest versions (including major updates), use the following methods:
1. Using npm-check-updates (Recommended)
This tool updates your package.json to reflect the latest versions of all dependencies, ignoring existing semver ranges.
Step 1: Install the tool globally
npm install -g npm-check-updates
Step 2: Update package.json
ncu -u # Updates package.json to latest versions
Step 3: Install the new versions
npm install # Installs the updated dependencies
Example Workflow
# Before: package.json shows "dependencies": { "lodash": "^4.17.20" }
ncu -u # Updates to "lodash": "^4.17.21" (or latest major version)
npm install # Installs the new version
2. Using Native npm Commands
For a npm-native approach (without third-party tools):
Update All Dependencies to Latest
npm install $(npm outdated | awk 'NR>1 {print $1"@latest"}') --save
Explanation
npm outdated: Lists outdated packages.awk: Extracts package names and appends@latest.npm install: Installs the latest versions and updatespackage.json.
3. Update Specific Dependency Types
Update Only dependencies
npm install $(npx -q npm-check-updates -o /dev/stdout) --save
Update Only devDependencies
npm install $(npx -q npm-check-updates -D -o /dev/stdout) --save-dev
4. Manual Updates (For Selective Control)
Update a Single Package
npm install lodash@latest --save
Check for Outdated Packages
npm outdated
# Sample output:
# Package Current Wanted Latest
# lodash 4.17.20 4.17.21 4.17.21
Key Considerations
- Breaking Changes:
- Major version updates (
v1.0.0 → v2.0.0) may introduce breaking changes. Test thoroughly. - Use tools like
npm testor CI/CD pipelines to validate updates.
- Security Updates:
npm audit fix # Automatically fix vulnerabilities
- Lockfile:
- Delete
package-lock.jsonoryarn.lockbefore runningnpm installto regenerate it.
- Semantic Versioning:
^1.2.3allows minor/patch updates (e.g.,1.3.0).~1.2.3allows patch updates only (e.g.,1.2.4).
Example Output
Before (package.json):
{
"dependencies": {
"react": "^17.0.1",
"lodash": "^4.17.20"
}
}
After running ncu -u:
{
"dependencies": {
"react": "^18.2.0", // Latest major version
"lodash": "^4.17.21" // Latest minor/patch
}
}
Troubleshooting
- If updates fail, delete
node_modulesandpackage-lock.json, then retry. - For monorepos, use tools like
lernaoryarn workspaces.
By following these steps, you can keep your project dependencies up-to-date with minimal effort.