There is no visible harm in having code in the code base, that is never used. Previously this at least would affect bundle size by increasing it without reason. However, introducing tree shaking in Webpack mostly removed even this reason. So, why to bother?
I would name just a few reasons, that I still see in keeping codebase crystal clear:
- do not confuse newcomers. If something exists, but it is not used – why would it be present? Should it be used? etc.
- decrease scopes of potential refactoring. For example, you decide to move from JS to TS, this will mean, that even when code is not actively used it will still contribute to the amount of work, that needs to be done.
Most of the unused code can be quite easily be caught with proper eslint rule, for example, no-unused-vars. However, when something is
export-ed it is no longer so easy to detect that it is no longer used. eslint-plugin-import has no-unused-modules rule, but it never worked for me on the codebase where I wanted to use it.
Last month, I found this nice repo js-unused-exports, that did exactly what I wanted it to do – detect all exports, that never been used in the readable format.
Usage is quite easy:
- You’ll need to install it globally with
npm install -g js-unused-exports
- Use it with command
js-unused-exports --config "unused-exports-config.json"
Examples of the config can be found in the repo.
My experience with this tool:
- The most suitable way for the output is in the cli. Library provides the ability to write output in the file, though data there is written in the format of the AST data, and is less easy to work with unless you are planning to source it to some other tool.
- Detection is quite reliable, but still, keep your eyes open, and do not delete everything that was detected unconsciously. For example, some of the files might be configured in a way, when their exports are automatically used by some tool (in my case all stories files, that were used for creating Storybook were such. Other case is that it just didn’t cover some of the cases. For example, at the moment of writing, it was not detecting dynamic imports properly.
With all that I would say this great reliable little helper. I would love to have something like this to work on CI directly, so instead of cleaning codebase, we would be able to detect when engineers are leaving unused code in the codebase, and encourage them to delete it.