Using the semver package I didn't see a simple way to check if I need a version of a library whether I have a compatible version. That made me wonder if I'm missing something obvious since it would seem like a common operation.
According to the Semver.org any version that is the same or new but is not in a new major version is supposed to be compatible. Therefore if I need 1.2.3
and I have >=1.2.3 <2.0.0
then it's all good. I can build that comparison by hand, it just seems so common that I'm curious if I'm missing a simpler way.
In other words, it appears I apparently have to do this
var canUse = function(need, have) {
var nextMajorVersion = semver.inc(need, 'major');
return semver.satisfies(have, '>=' + need + ' && ' + '<' + nextMajorVersion);
};
Which works
canUse('1.2.3', '1.2.3'); // true
canUse('1.2.3', '1.2.4'); // true
canUse('1.2.3', '1.3.0'); // true
canUse('1.2.3', '0.4.4'); // false
canUse('1.2.3', '2.4.4'); // false
Yes, it's a tiny piece of code. It just seemed like that would be such a common operation that I wouldn't have to manipulate strings and manually build a range comparison just to check what seems like it a common question, is X compatible with Y.
Is there an easier way?
The caret operator should create the expected range in most cases:
^1.2.3
:=>=1.2.3-0 <2.0.0-0
"Compatible with1.2.3
". When using caret operators, anything from the specified version (including prerelease) will be supported up to, but not including, the next major version (or its prereleases).1.5.1
will satisfy^1.2.3
, while1.2.2
and2.0.0-beta
will not.
semver.satisfies('1.2.3', '^1.2.3') // true
semver.satisfies('1.2.4', '^1.2.3') // true
semver.satisfies('1.3.0', '^1.2.3') // true
semver.satisfies('0.4.4', '^1.2.3') // false
semver.satisfies('2.4.4', '^1.2.3') // false
The exception is with 0.x.x
versions. For these, a ^
will be ignored.
^0.1.3
:=0.1.3
"Compatible with0.1.3
".0.x.x
versions are special: since the semver spec specifies that0.x.x
versions make no stability guarantees, only the version specified is considered valid.
semver.satisfies('0.8.9', '^0.1.0') // false