Find unused `npm` dependencies by Josh Sherman

By Josh Sherman

Josh Sherman

2 min read

As much as I love to sling code, I love that we live in a world where you can stand on the shoulders of giants and easily leverage other people’s hard work by way of Open Source libraries.

Simply referred to as “dependencies”, these little code gems can save a ton of time. Unfortunately though, especially with a larger code base with multiple contributors, these dependencies can stack up quick.

Not only do they stack up, eventually the day comes when a better library is brought into the fold, and the original dependency or dependencies stop being used entirely.

The typical scenario I’ve seen at different points in my career would be 2-3 of the same exact type of library installed, but only one of them is actually still in use.

For whatever reason, it never fails that it’s a CSV parsing library. Not sure why we can’t seem to agree on one CSV parser to rule them all out in Node.js land.

With these dependencies that aren’t being used still in the fold, build times grow increasingly longer as we’re installing code unnecessarily over and over and over.

Fortunately, like most problems you face in development, there’s another somebody or somebodies that have already run into the issue and have put the time and effort into concocting a solution.

For npm dependencies, that solution is depcheck, a handy little library that will scan your code and identify any unused dependencies.

If you have a Node.js project handy, you can follow along at home.

To run depcheck you can use npx within your project:

And that’s it! npx will install depcheck and run it for you.

If you’re lucky, the output of the command will be No depcheck issue, but if you have any unused dependencies, you’ll see output similar to this:

Unused dependencies
* some-unused-dependency
* some-other-unused-dependency
Unused devDependencies
* et-cetera-etc-cetera

As an added bonus, depcheck will also identify any dependencies you are using that aren’t explicitly listed in your package.json file, which looks like this:

Missing dependencies
* something-not-listed

Pretty handy and quick and easy to make the most of it. Bonus points awarded to folks that take a minute to wire depcheck up to automatically run these checks on commit and/or push to make sure you’re always on top of your unused dependencies!

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.