Tobias Davis

Designing better software systems.

Articles | Contact | Newsletter | RSS

Site logo image

Using semver ranges for git hosted npm modules

It’s pretty common for a company to have a few npm modules hosted on GitHub or BitBucket as private repositories. In this post I’ll show you how you can use semver ranges for those modules.

I’ve also created a demo module which is a public repository, but not published on npm, so to install it you need to use a git reference, e.g.:

npm install --save git+ssh://[email protected]/saibotsivad/demo-npm-git-semver.git

The module exports a function that returns it’s own version when called, so you can make sure you’ve installed it correctly and see what version is installed:

const demo = require('demo-npm-git-semver')
console.log(demo()) // => ???

The problem here is that you don’t have any control over what version you installed! You get whatever the git server marks as the head of the default branch.

This might be fine for some applications, but for most production systems you’ll want to be able to specify versions.

One solution is to use the commit hash:

npm install --save git+ssh://[email protected]/saibotsivad/demo-npm-git-semver.git#1cbcec73

But what we really want is to be able to use proper semver ranges (see also this handy semver calculator), that way we can leverage the power of semver.

Conveniently, npm allows you to specify a semver range instead of a hash!

The magic syntax is to use semver:$RANGE instead of a commit hash. For example, if you wanted to specify at least version 1.0.3 but use the latest 1.x.y whenever available:

npm install --save git+ssh://[email protected]/saibotsivad/demo-npm-git-semver.git#semver:^1.0.3

In that demo repository, the highest 1.x version that I created is 1.1.3, so that’s what will be installed:

const demo = require('demo-npm-git-semver')
console.log(demo()) // => 1.1.3

That’s all!

If you’re having trouble getting your private repository working, don’t hesitate to message me!


Your thoughts and feedback are always welcome! 🙇‍♂️