I’ve been working on a React project for several months, and after many rounds of testing different libraries, my node_modules folder has ballooned in size. I’ve noticed that even after deleting dependencies from my package.json file, the actual files still remain in the local directory. Is there a built-in command for NPM or Yarn to perform a "prune" operation that automatically detects and deletes these orphaned packages without me having to manually nuke the entire folder and reinstall?
3 answers
The most direct way to handle this in a standard Node.js environment is by using the npm prune command. This command is specifically designed to cross-reference your node_modules folder with the dependencies listed in your package.json and automatically remove any "extraneous" packages that don't belong there. If you want to see what will be removed before actually deleting anything, you can run npm prune --dry-run. For those of you working in production environments, running npm prune --production is also a great way to strip out devDependencies and keep your deployment image as slim as possible. It is much faster than the "delete and reinstall" method and keeps your local development environment perfectly synced with your configuration.
I’ve tried npm prune, but sometimes it feels like it misses nested transitive dependencies that were left over from a manual install. Would it be safer to just use npm ci in my CI/CD pipeline to ensure a 100% clean slate every time we build, or is that overkill for a local development setup where I'm just trying to save some disk space?
Just run npm prune in your terminal. It’s built-in and does exactly what you’re asking by removing anything not found in your dependency list.
I agree with Jessica. I recently integrated npm prune as a pre-commit hook in our team’s workflow. It ensures that no developer accidentally leaves behind massive, unused binaries that might interfere with local testing or bloat our Docker containers during the initial build phase.
David, npm ci is definitely the gold standard for CI/CD because it effectively nukes the node_modules and reinstalls exactly what is in your package-lock.json. For local dev, though, it can be a bit slow if you have a massive project. If npm prune is failing you, check for a yarn autoclean equivalent if you've switched managers, or simply use a utility like rimraf to wipe the folder. Just remember that npm ci requires an existing lockfile to work, so if you've been manually editing package.json without updating the lockfile, it might actually throw an error instead of cleaning.