Checking node.js dependencies with SZero – Never lose track again.

Node.js is a JavaScript runtime built on top of Chrome’s V8 JavaScript engine. It is highly event-driven, and leverages non-blocking I/O model that makes it lightweight, efficient, and incredibly productive to use. It’s that last bit, “productive”, that I want to focus on today.

One of the things that i feel makes Node(and NPM) so great is the ease in which you can add and use third-party modules. As most node.js developers know, to start using an external module, you first install it:

npm install cool-module --save

Then we require it:

const coolModule = require('cool-module');

Then we use it:

coolModule.doCoolStuff();

Yup, pretty easy.

However, as most node.js developers know, our dependency list in our pacakge.json can grow pretty quickly. And sometimes we lose track of where in our code we are using these dependencies. Sometimes, dare I say it, we have modules in our package.json that we don’t actually use. GASP!!!

Ok, so if you’ve made it this far, then you probably realize this next paragraph is going to talk about how Szero fits into what i wrote above. Productivity, package installation, and dependency management/location.

What is SZero

SZero is a small library that we, a small team at Red Hat, have written. It checks the dependencies you’re using, and locates them in your code.

Let’s see an example.

To get started, we need to install, preferably globally, but there is also an API that can be used

npm install szero -g

Lets say i have a project with two dependencies, so my package.json would have something like this

So what does all that mean? Well, in the first section, we see where we required the module and what the variable name we stored it in. We also see the line numbers where we use that variable. So since we stored the coolModule module in a variable called coolModule, that is why we get this format:

coolModule-require('coolModule'):

In the next section, SZero counts up the usage:

coolModule-require('coolModule') --> [ 2 ]

And the last section shows, if any, unused dependencies.

I think this feature is very useful. I know there have been many times where i install something, then don’t end up using it, but forget to uninstall it. Speaking of unused dependencies, you can specify the --ci flag if you are running in a CI environment, so if any unused dependencies are detected, it will fail your build.

By default, the output from running szero will output directly to the console, but you can specify the --file flag to output to a file. So now lets see the command in action using an animated Gif: