前端工程化项目 中,package.json 中的 版本号 通常遵循 语义化版本 (Semantic Versioning, SemVer) 规范。
每个依赖项的版本号格式通常为:

主版本号.次版本号.修订号
MAJOR.MINOR.PATCH

示例:

"dependencies": {
  "react": "^19.0.0",
  "axios": "~1.5.0",
  "lodash": "4.17.21",
  "date-fns": ">=2.28.0"
}

📌 1. 语义化版本 (SemVer) 规则

版本格式说明
1.0.0完整版本号MAJOR.MINOR.PATCH
^1.2.3兼容模式:允许 1.x.x(但不允许 2.0.0
~1.2.3补丁更新:允许 1.2.x(但不允许 1.3.0
>=1.2.3最小版本:允许 1.2.3 及以上版本
<2.0.0最大版本:允许低于 2.0.0 的所有版本
latest最新版本:始终安装最新版本

📌 2. 版本号前缀的意义

^ (Caret) —— 向上兼容(默认)

"react": "^19.0.0"
  • 允许更新 次版本 (MINOR) 和修订 (PATCH),但不允许升级主版本 (MAJOR)
  • 例如:

    • ✔ 允许: 19.0.1, 19.1.0, 19.9.9
    • ❌ 不允许: 20.0.0

~ (Tilde) —— 仅允许修订 (PATCH) 版本更新

"axios": "~1.5.0"
  • 允许更新 修订 (PATCH),但不允许次版本 (MINOR) 更新
  • 例如:

    • ✔ 允许: 1.5.1, 1.5.9
    • ❌ 不允许: 1.6.0

>= (Greater than or equal) / < (Less than)

"lodash": ">=4.17.21"
  • >=4.17.21:安装 4.17.21 及更高版本(包括 5.0.0)。
  • <2.0.0:安装 2.0.0 之前的版本(但不包含 2.0.0)。

* (任意版本)

"express": "*"
  • 允许任何可用版本(通常不推荐)。

📌 3. dependencies vs devDependencies

字段作用
dependencies生产环境依赖,项目运行时需要的库(如 reactaxios
devDependencies开发环境依赖,仅在本地开发和构建时需要(如 eslintwebpack

示例:

"dependencies": {
  "react": "^19.0.0",
  "axios": "^1.5.0"
},
"devDependencies": {
  "eslint": "^8.50.0",
  "webpack": "^5.89.0"
}

📌 4. peerDependencies vs optionalDependencies

字段作用
peerDependencies建议使用的依赖,通常用于插件或库(如 react 组件库需要 react
optionalDependencies可选依赖,如果安装失败不会影响其他依赖

示例:

"peerDependencies": {
  "react": "^19.0.0"
},
"optionalDependencies": {
  "fsevents": "^2.3.2"
}
  • peerDependencies 主要用于库开发,不会自动安装,要求用户在项目中手动安装兼容版本。
  • optionalDependencies 适用于非关键依赖,如果安装失败不会影响整个项目。

📌 5. overrides / resolutions

overrides(适用于 npm

"overrides": {
  "react": "^19.0.0"
}
  • 强制指定 react 的版本,适用于 npm

resolutions(适用于 Yarn / pnpm

"resolutions": {
  "react": "^19.0.0"
}
  • 强制所有依赖使用 react@19.0.0,但不会自动安装它。

📌 6. engines(Node.js 版本约束)

"engines": {
  "node": ">=18.0.0"
}
  • 强制要求项目在 Node.js 18.0.0 及以上版本运行。

📌 7. 总结

写法作用
"react": "19.0.0"仅安装 19.0.0
"react": "^19.0.0"允许 19.x.x,但不允许 20.0.0
"react": "~19.0.0"允许 19.0.x,但不允许 19.1.0
"react": ">=19.0.0"允许 19.0.0 及以上版本
"react": "*"安装任何可用版本(不推荐)
"overrides"npm 强制版本
"resolutions"Yarn / pnpm 强制版本

这样可以让 package.json 版本管理更加清晰!🚀