Finding dead or unused TypeScript code (unused exports)
Like any programming language, if a project gets quite large, tooling can help to find dead (unused) code.
Dead code whilst seemingly innocuous, can waste developer time:
- reading code that does nothing
- refactoring code that is not needed
- cognitive overhead of mentally filtering out code that is not called anymore
Whilst IDEs such as Visual Code can provide visual indicators of unused TypeScript functions, and show when a function has 'zero references', there is one case that is technically tricky to detect:
- unused exports
A TypeScript file (which, depending on your environment, is a module) can export a function, but without checking for project-wide usage, it is not safe to assume that the function is dead code.
Most linters such as eslint and the older tslint generally operate "one file at a time", partly for performance reasons. So, obviously these linting tools find it trick to detect "unused exports".
Tools to the rescue
Some open source tools have been created to help find unused exports:
(disclaimer: this author is a contributor!) Reasonably popular choice which covers simpler TypeScript environments. Has some support for advanced cases such as dynamic imports.
aside: uses an interesting "Behaviour Driven Development (BDD)" style unit testing library named pickled-cucumber.
2 - ts-prune
More popular again than ts-unused-exports and has a lot of articles and usages on the internet.
3 - eslint rule no-unused-modules
An eslint rule to find unused exports. Interesting source code, using visitor pattern.
If you think of other useful tools, please comment below. Thank you.
Comments
Post a Comment