Why clean up unused dependencies?
Keeping your project clean and efficient is crucial, especially when dealing with dependencies. Over time, unused libraries can accumulate, bloating your node_modules folder and potentially causing conflicts. In this post, I'll show you how I used depcheck to identify and remove unnecessary dependencies from a Node.js project.
What depcheck does and what it needs
- Tool Used: depcheck
- Purpose: Find unused npm packages and clean up your
node_modules - Prerequisite: Your project must contain a
package.jsonfile
How to remove unused packages with depcheck
Install depcheck, run it in the folder that holds your package.json, review what it lists and remove what you do not need.
-
Install depcheck Globally
To begin, installdepcheckglobally on your system by running:bashnpm install -g depcheck -
Run depcheck
Navigate to the folder where you want to check for unused dependencies. Make sure this folder contains yourpackage.jsonfile. Run the following command:bashdepcheck -
Review the Output
If you’ve installed a package, sayreact-bootstrap, but haven’t imported anything from it,depcheckwill list it underUnused dependencies. Example Output:bashUnused dependencies * react-bootstrap Missing dependencies * ... -
Remove Unused Packages
Once identified, you can remove any unwanted packages by running:bashnpm uninstall <package_name>For example:
bashnpm uninstall react-bootstrap
What removing unused dependencies gets you
Fewer dependencies mean faster installs and deployments, a smaller attack surface and a project that is easier to maintain.
- Improved Performance: Smaller
node_modulesdirectory resulting in faster installations and deployments. - Reduced Security Risks: Fewer dependencies reduce the attack surface for potential vulnerabilities.
- Cleaner Codebase: Less clutter means a more maintainable project.
Limitations
depcheckmay occasionally report false positives, particularly for packages used dynamically (e.g., viarequire()or with unconventional import structures).- Dependencies listed as
peerDependenciesordevDependenciesmay require careful consideration before removal.
Keeping a project free of unused dependencies
Using depcheck is a straightforward way to ensure your Node.js projects remain free from unnecessary dependencies. Regularly running this tool can help you maintain a cleaner and more efficient codebase.
Further Reading
For more details, refer to the official depcheck documentation.
See the six things I am hired to do and how an engagement runs.
