Semver carets and tilde in npm

If you use npm you have likely seen notation for dependencies in your package.json like ^4.2.7 or ~3.5.3, etc. Those are respectively caret ranges and tilde ranges. They are well documented on the npm website.

And while I have become quite familiar on how to use them, I had an epiphany recently that I thought I would share. This could help newbies navigate these powerful yet odd notation.

The main power of those notations versus their easier-to-understand cousins x, X and * is that you can fix the lowest version. This is usually critical, because when everybody follows semantic versioning, a library is backward compatible, but your code, as the consumer, does not have to be. Actually, it is only forward compatible.

Let’s say you use a library called foo. The authors of foo, at version 1.2 decide to introduce a cool new bar() method in their package. You want to take advantage of bar() in your code.
If you used the x notation in your package.json, like this:

"foo": "1.x",

It would be technically correct for someone either using your package or a dev on your team to install version 1.0 or 1.1 of the foo package. They both satisfy the 1.x semver. However, bar() is only in 1.2 and later.

By using the ^ or ~ notation, you can prevent that by using:

"foo": "~1.2",

This tells npm that it must have at least version 1.2 but after that, any 1.x version will work with your code.

I hope this helps at least one new person to semantic versioning make sense of this powerful notation.

Comments

Popular posts from this blog

Running Karma in specific TimeZone

Calling HttpClient async functions from constructors in ASP.NET 4.5