When we open our package.json file and search for dependency property and in there we find the packages that are listed as a nested object of the dependency property package-name:package-version. Now look at the package version, we find some numbers separated by three dots (e.g. 2.6.2).
NPM versions are written using three dots separated numbers the first number from the left shows the major release and the second number from the left shows the minor release and the third number shows the patch release of the package.
Syntax: The syntax of the npm version looks like the following.
Major.Minor.Patch
Tilde (~) notation: It is used to match the most recent patch version. Tilde ~ notation freezes the major version and minor version. As we know patch updates are bug fixes that’s why we can say ~ notation allows us to automatically accept bug fixes.
Example: The ~1.2.0 will update all the future patch updates. We have to write just ~1.2.0 and all the next patch update dependencies. For example, 1.2.1, 1.2.2, 1.2.5……………1.2.x.
Note: Patch updates are very small security changes in a package that is why the ~version is approximately equivalent to the version.
Caret (^) notation: It is used for automatically updating the minor updates along with patch updates.
Example: The ^1.2.4 will update all the future Minor and patch updates, for example, ^1.2.4 will automatically change the dependency to 1.x.x if any update occurs.
Using caret notation it is important to look at our code regularly if it is compatible with the newest version or not.
Difference between tilde (~) and caret (^) in package.json:
Tilde(~) notation |
Caret(^) notation |
Used for Approximately equivalent to version. | Used for Compatible with version. |
It will update you to all future patch versions, without incrementing the minor version. ~1.2.3 will use releases from 1.2.3 to <1.3. | It will update you to all future minor/patch versions, without incrementing the major version. ^2.3.4 will use releases from 2.3.4 to <3.0.0 |
It gives you bug fix releases. | It gives you backwards-compatible new functionality as well. |
It will update in decimals. | It will update to its latest version in numbers. |
Not a default notation used by NPM. | Used by NPM as default notation. |
Example: ~1.0.2 | Example: ^1.0.2 |
References: https://docs.npmjs.com/about-semantic-versioning