Semver Checker & Range Tester · Tutorial
How to read ^ and ~ version ranges in package.json
6 min readbeginnerUpdated
Your package.json says "lodash": "^4.17.0", but which versions will npm actually install? You will test the range against a list of releases, compare it with a tilde range, and learn the special rule for versions below 1.0.
What you need
- The Semver Checker
- A package.json, or just the range you want to understand
Steps
Test the caret range
Load the example. The range
^4.17.0reads “at least 4.17.0 and below 5.0.0”. Of the listed versions, 4.17.0, 4.17.21 and 4.18.2 match. 4.16.6 is too old and 5.0.0 is a new major version.Notice the pre-release
4.18.0-rc.1is marked as not matching even though 4.18 is inside the range. npm skips pre-releases unless you ask for them. Tick Include pre-releases to see the difference.Try a tilde range
Change the range to
~4.17.0. Now only 4.17.x versions match, so 4.18.2 is excluded. Use a tilde when you only want bug fixes.^4.17.0 → >=4.17.0 <5.0.0 ~4.17.0 → >=4.17.0 <4.18.0Check a 0.x dependency
Type
^0.4.2. It means “below 0.5.0”, not “below 1.0.0”, because before 1.0 every minor release may break things. Many surprise upgrades come from forgetting this.See what a fresh install picks
The Highest match is the version npm chooses when there is no lockfile. Paste the versions from
npm view <package> versionsto check against the real list.
Try it yourself
Opens the Semver Checker & Range Tester with this tutorial's sample loaded.
Common mistakes
- Thinking the range is what you have installed
- The lockfile decides what is installed. The range only matters when the lockfile is updated or missing, for example with
npm update. - Using * or latest for dependencies
- They allow any new major version, which can break your build on the next install. Use a caret range and update on purpose.
Next steps
Go back to the Semver Checker & Range Tester, or keep going with one of these:
FAQ
Is ^ the default when I run npm install?
Yes. npm install lodash saves ^ plus the current version. You can change this with npm config set save-prefix ~.