Using the NPM API to Get Latest Package Versions

The official npm API provides a simple way to programmatically retrieve the latest version of any package, along with other metadata you might find in the package.json. This has a variety of use cases, such as checking when a package is out of date, to name one example. Today I’ll demonstrate how to get the latest version of a package with only a few lines of code. However, I was frustrated with what I found in other solutions, so I also want to talk about those and why you shouldn’t use them.

A very popular way to get the latest version is through the latest-version package on npm, which has nearly 3 million weekly downloads. The package sports a shiny build passing badge (so you know it’s good), and the README even tells you why you should choose this package over the latest package, which has “massive” dependencies. The code example also looks pretty slick:

1
2
console.log(await latestVersion('ava'));
//=> '0.18.0'

So my first impression is that the package is popular, reliable, more lightweight than the competition, and simple to use. Sounds great to me! Let’s just check the download size before installing…

Bundle Size according to bundlephobia.com

Wait a minute… This package literally exposes one function that does one thing. How on earth could it possibly require nearly 90kB, minified?! It turns out that the culprit is the package’s only (and much more useful) dependency, package-json, which allows you to extract information from any package.json file on npm.

The crime here (in my opinion) is that this dependency is over-qualified; it feels a lot like cracking an egg with a hammer. Moreover, the hammer itself is overkill, as the npm API already provides this information. We can do better:

A Better Solution

Using the npm API and the much lighter-weight dependency, axios, we can rewrite the entire latest-version module in a handful of lines:

1
2
3
4
5
function latestVersion(packageName) {
return axios
.get('https://registry.npmjs.org/' + packageName + '/latest')
.then(res => res.data.version);
}

Just like the original package, latestVersion() returns a promise, so you can use it exactly the same as the latest-version docs describe:

1
const packageVersion = await latestVersion('some-package');

Conclusion

I hope this saved you some unnecessary code bloat. If you want to see how other packages will affect your bundle size in the future, you can check for yourself at bundlephobia.com.

Creating an Engraved Leather Effect with CSS

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×