In Node.js package.json
, the tilde (~
) and caret (^
) symbols define version ranges for dependencies using Semantic Versioning (SemVer). They control how npm updates packages when running commands like npm update
or npm install
.
1. Tilde ~
(Patch Updates)
Allows patch-level changes (the third number in major.minor.patch
).
- Format:
~X.Y.Z
- Behavior:
- Updates to the latest
X.Y.*
version, but keepsX.Y
fixed. - Example:
~1.2.3
→ Accepts1.2.4
,1.2.9
, etc., but not1.3.0
or2.0.0
.
- For
0.x
versions (pre-1.0):~0.1.2
→ Accepts0.1.3
,0.1.4
, etc., but not0.2.0
.
2. Caret ^
(Minor & Patch Updates)
Allows minor and patch-level changes (the second and third numbers).
- Format:
^X.Y.Z
- Behavior:
- Updates to the latest
X.*.*
version, keepingX
fixed. - Example:
^1.2.3
→ Accepts1.3.0
,1.9.0
, etc., but not2.0.0
.
- For
0.x
versions (pre-1.0):^0.1.2
→ Behaves like~0.1.2
(only patch updates).^0.2.0
→ Accepts0.2.1
,0.2.2
, etc., but not0.3.0
.
Key Differences
Scenario | Tilde (~ ) | Caret (^ ) |
---|---|---|
Stable (v1+) | Patch updates only. | Minor + patch updates. |
Pre-1.0 (0.x ) | Patch updates only. | Patch updates only. |
Example (v1.2.3) | 1.2.3 → 1.2.9 | 1.2.3 → 1.9.9 |
When to Use Which
- Use
~
to lock minor versions (e.g., avoid unexpected minor changes). - Use
^
to accept new features (minor updates) but avoid breaking changes (major updates). - For
0.x
versions,~
and^
behave similarly (patch updates only).
Examples
{
"dependencies": {
"lodash": "^4.17.21", // Accepts 4.x.x (latest minor/patch)
"express": "~4.18.2" // Accepts 4.18.x (latest patch)
}
}
Notes
- Use exact versions (e.g.,
1.2.3
) for critical dependencies. - Always test updates, as even minor/patch changes can introduce bugs.
- Lock files (
package-lock.json
/yarn.lock
) pin versions to ensure consistency.
By choosing ~
or ^
, you balance stability with access to updates.