What's the difference between tilde(~) and caret(^) in package.json?
When you look at the dependencies in a package.json
file, you often see version numbers prefixed with tilde (~
) or caret (^
). These symbols define how npm (or yarn) handles semantic versioning (SemVer) when installing dependencies.
1. Semantic Versioning Basics
A standard semantic version is in the form major.minor.patch
:
major
: Incompatible API changes (breaking changes)minor
: Backward-compatible new featurespatch
: Backward-compatible bug fixes
So a version like 2.3.4
corresponds to:
- major:
2
- minor:
3
- patch:
4
2. Tilde (~
) — Patch-Level Flexibility
A tilde in front of the version ensures that npm or yarn will install patch updates, while minor and major stay fixed.
- Example:
"lodash": "~4.17.5"
- npm will install the latest patch version matching
4.17.x
. - So it can install
4.17.6
,4.17.7
, etc. - It won’t install
4.18.0
or anything higher.
- npm will install the latest patch version matching
Why Use Tilde?
- You want to allow bug fixes (patch updates) but avoid automatically pulling in new minor features that might introduce unexpected changes.
3. Caret (^
) — Minor-Level Flexibility
A caret allows npm or yarn to install both patch and minor updates, but keeps the major version locked.
- Example:
"react": "^17.0.2"
- npm can install any
17.x.x
version, such as17.1.0
,17.2.3
, etc. - It won’t install
18.0.0
because that changes the major version.
- npm can install any
Why Use Caret?
- You’re comfortable with minor updates (which should be backward-compatible) and bug fixes, but want to avoid breaking changes that come with a new major version.
4. Choosing Between ~
and ^
- Use
~
if you only want patch-level updates. This is the most conservative approach, ensuring fewer surprise changes but possibly missing out on minor improvements. - Use
^
if you’re okay with minor and patch updates. This is the default in most npm/Yarn setups because minor releases are intended to be backward-compatible, while you still avoid major breaking changes.
5. Examples
-
"axios": "~0.21.1"
- Installs patch releases:
0.21.2
,0.21.3
, etc. - Avoids minor increments like
0.22.0
.
- Installs patch releases:
-
"axios": "^0.21.1"
- Installs patch and minor releases:
0.21.2
,0.22.0
, etc. - Avoids major releases like
1.0.0
.
- Installs patch and minor releases:
Recommended Resources
Conclusion
- Tilde (
~
): Restricts updates to patch versions within the specified minor release. - Caret (
^
): Allows patch and minor updates, but locks down the major version.
Understanding these symbols helps you control how your dependencies get updated, balancing stability against staying current with new releases.
CONTRIBUTOR
TechGrind