Detect and Remove Unused Dependencies in Projects
Recently when looking at some projects, I found many dependencies. After searching a few randomly, I discovered they weren’t being used and could be removed. However, checking and removing these packages one by one is too troublesome.
Based on this need, I wrote a small tool to efficiently detect and remove unused dependencies.
@stacker/remove-unused-deps
Usage: Execute the following command in the project root directory, interactively select unused dependencies, and press enter to uninstall and remove them.
1 | npx @stacker/remove-unused-deps@latest |
Principle
- depcheck: This tool is excellent mainly because it can detect unused dependencies and development dependencies in projects. However, it has the drawback of only outputting unused dependencies without actively uninstalling them. Therefore, it must be combined with other tools to complete the task.
- fs scans the project’s lock file to determine whether the package manager is yarn or npm
- Build an interactive command line that executes the corresponding uninstall command after the user selects the dependencies to be removed
Special Case Packages
Some packages, although detected as unused, may not be unnecessary but are needed in the project. For example, if the project depends on package A and package A uses package B, but package B isn’t listed in the dependencies, manual user confirmation is still needed.
At the end
With this tool, it’s convenient to detect and remove unused dependencies in projects.
Removing unused packages helps clarify project dependencies and prevents developers from using packages just because they’re available, which can lead to multiple solution packages coexisting in the project.
Currently, this tool only supports yarn and npm; other package managers are not yet supported. However, as demand increases, this will be supported later.