如何将package.json中的每个依赖项更新到最新版本

如何将package.json中的每个依赖项更新到最新版本

技术背景

在前端开发中,项目的 package.json 文件管理着项目的依赖信息。随着时间推移,依赖项可能会发布新的版本,包含性能优化、功能增强和安全修复等。因此,将依赖项更新到最新版本对于项目的稳定性和安全性至关重要。

实现步骤

使用 npm-check-updates

npm-check-updates 是一个实用工具,可自动将 package.json 文件中的所有依赖项更新到最新版本。

  • 全局安装并使用
1
2
3
npm i -g npm-check-updates
ncu -u
npm install
  • 使用 npx(避免全局安装)
1
2
npx npm-check-updates -u
npm install

对于旧版本 npm(<3.11)

将每个依赖项的版本改为 *,然后运行 npm update --save

1
2
3
4
5
6
7
8
9
// 修改前
"dependencies": {
"express": "*",
"mongodb": "*",
"underscore": "*",
"rjs": "*",
"jade": "*",
"async": "*"
}
1
2
3
4
5
6
7
8
9
// 修改后
"dependencies": {
"express": "~3.2.0",
"mongodb": "~1.2.14",
"underscore": "~1.4.4",
"rjs": "~2.10.0",
"jade": "~0.29.0",
"async": "~0.2.7"
}

npm 2+(Node.js 0.12+)

1
2
3
npm outdated
npm update
git commit package-lock.json

旧版 npm(约2014年)

1
2
3
4
npm install -g npm-check-updates
npm-check-updates
npm shrinkwrap
git commit package-lock.json

更新单个依赖项

1
2
3
npm install {package-name}@* {save flags?}
# 示例
npm install express@* --save

对于工作区:

1
npm --workspace some/package install express@*

使用 yarn

  • 更新所有包到最新版本:
1
yarn upgrade --latest
  • 交互式更新:
1
yarn upgrade-interactive --latest

使用 Updtr

1
2
3
4
# 安装 Updtr
npm install -g updtr
# 运行更新
updtr

核心代码

使用 npm-check-updates

1
npx npm-check-updates -u && npm i

使用正则表达式批量替换版本号

1
([>|<=|~|^|\s])*?(\d+\.)?(\d+\.)?(*|\d+)

使用 jqxargs 更新依赖

1
2
3
npm outdated --json --depth=0 | \
jq --ascii-output --monochrome-output '. | keys | .[]' | \
xargs npm install $1 --save-dev

最佳实践

  1. 使用 npm outdatednpm-check-updates 建议最新版本
1
2
3
4
5
6
7
8
9
10
11
npm outdated
# 如果同意,进行更新
npm update

# 或者
# 安装并使用 `npm-check-updates` 包
npm install -g npm-check-updates
# 检查项目
npm-check-updates
# 如果同意,更新 package.json
npm-check-updates -u
  1. 进行干净安装
1
2
rm -rf node_modules
npm install
  1. 使用 npm shrinkwrap 保存精确版本到 npm-shrinkwrap.json
1
2
rm npm-shrinkwrap.json
npm shrinkwrap

常见问题

  1. 更新到不稳定版本npm-check-updates 可能会将模块更新到最新版本,包括不稳定的 alpha 版本。可以使用 latest 版本定义来获取最新稳定版本。
  2. --save-dev 的含义--save-dev 表示将包添加到 devDependencies 中。
1
npm install @progress/kendo-angular-dateinputs@latest --save-dev
  1. npm update 不更新到最新版本npm update 基于语义化版本进行更新,可能不会更新到最新的主版本。可以使用 npm install <packagename>@latest 来更新到最新主版本。

如何将package.json中的每个依赖项更新到最新版本
https://119291.xyz/posts/2025-05-12.how-to-update-dependencies-in-package-json/
作者
ww
发布于
2025年5月12日
许可协议