This quick article explains how to clean up all dependencies installed with npm or yarn, and stored in folders called “node_modules” within your project and solution files. This regrettable step might be required to either free some disk space or clear weirdly broken dependencies from your project(s). Hope this will be as helpful to you as it’s been to me 🙄
Background
npm and yarn install all dependencies, and dependencies of dependencies, and dependencies of those dependencies of dependencies, and so on, in a folder called node_modules. If you have a bunch of projects in your solution, each will have a completely isolated and independent node_modules folder on its own.
These folders can take hundreds and hundreds of megabytes per project – and npm might not always be great at managing the file versions in those directories.
So long story short, even if you don’t have to free some disk space, you might occasionally need to remove the node_modules folders.
Anyway – let’s get to it, then!
Solution
PowerShell is, well, a very powerful shell, but starting with what I thought would be the most obvious commandlet, Remove-Item, I couldn’t easily figure out a way to recursively and silently remove all folders called node_modules within a file structure.
But with PowerShell, there’s always another way to achieve your goals!
Instead of running Remove-Item -Filter -Recurse with increasingly obscure filters (or multiple different \*\*\node_modules\ -patterns), you can just fetch all node_modules directories with Get-ChildItem and then proceed to remove them one-by-one.
I don’t think it’s as fast as Remove-Item would be, but you’ll probably get there this way too.
cd C:/code/
$nodemodules = Get-ChildItem "node_modules" -Recurse -Force -Attributes "Directory"
$nodemodules.Count # For good measure
$nodemodules | Remove-Item -Recurse
If you want to first run the removal without, well, actually removing anything, you can replace the last line with this instead:
$nodemodules | Remove-Item -Recurse -WhatIf
Et voilà! You should be good with this.
- M365 Copilot claiming “You have turned off web search in the work mode”? Easy fix! - November 19, 2024
- “Performing cleanup” – Excel is stuck with an old, conflicted file and will never recover. - November 12, 2024
- How to add multiple app URIs for your Entra app registration? - November 5, 2024