TL;DR: Use ts-prune is in maintenance mode. Use knip to find dead code instead. It's great!
Three years ago I recommended using --noUnusedLocals
and ts-prune
to find dead code and dead types in your projects. ts-prune
worked well enough, but it's now in maintenance mode and won't be receiving updates. This is a fine decision and it's the responsible thing to do when you no longer plan to maintain an open source project (I sometimes struggle with this!).
While ts-prune
was effective at its core job, it always had a few shortcomings: it couldn't detect unused dependencies or mutually recursive dead code. It also made no attempts to understand whether your test code was alive or dead. So when I noticed that Josh's template-typescript-node-package was using a new tool called Knip, I was intrigued. Could this be the dead code removal tool of my dreams?
Basically, yes! knip
uses the same sort of mark-and-sweep algorithm as ts-prune
to find dead code (see my previous post for why this is what you want). But it's much more ambitious in the sorts of issues it tries to find:
- It will report unused
dependencies
and evendevDependencies
from yourpackage.json
. Removing these can be a huge win since it reduces your package size and eases the burden of keeping up to date with the latest versions. - It will report files that are never imported by non-test code.
- It will report missing dependencies. This can happen if you depend on
A
which depends onB
. You import something fromB
and it works, but you didn't list it in your dependencies. If you ever remove the dependency onA
, this will be a problem. Best to depend onB
directly if you use it directly. - It will report duplicate exports.
- It will report unused class members and enum members.
Because of the enormous diversity of JS/TS libraries and tools, you'd expect that explaining your project setup to a tool like knip
would involve writing a complicated configuration file. But that's usually not the case. knip's models this enormous diversity with an enormous collection of plugins. Chances are that your test runner and framework are already on the list.
Give knip
a try! You might be surprised at the dead code you've accumulated. You can use this PR as a template for setting it up in a project. Once you get down to zero errors, add knip
to your CI to ensure that you never have dead code again!