[node.js] How to clean node_modules folder of packages that are not in package.json?

Assume I install project packages with npm install that looks into package.json for modules to be installed. After a while I see that I don't need some specific module and remove its dependency from package.json. Then I remove some other modules from package.json because they are not needed anymore and others are replaced with alternatives.

Now I want to clean node_modules folder so that only modules listed in package.json stay there and the rest must go, something like npm clean. I know I can remove them manually but would like to have some nice ready to use sugar functionality for that.

This question is related to node.js package npm

The answer is


Just in-case somebody needs it, here's something I've done recently to resolve this:

npm ci - If you want to clean everything and install all packages from scratch:

-It does a clean install: if the node_modules folder exists, npm deletes it and installs a fresh one.

-It checks for consistency: if package-lock.json doesn’t exist or if it doesn’t match the contents of package.json, npm stops with an error.

https://docs.npmjs.com/cli/v6/commands/npm-ci

npm-dedupe - If you want to clean-up the current node_modules directory without deleting and re-installing all the packages

Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.

https://docs.npmjs.com/cli/v6/commands/npm-dedupe


rimraf is an package for simulate linux command [rm -rf] in windows. which is useful for cross platform support. for install its CLI:

npm install rimraf -g

The best article I found about it is this one: https://trilon.io/blog/how-to-delete-all-nodemodules-recursively

All from the console and easy to execute from any folder point.

But as a summary of the article, this command to find the size for each node_module folder found in different projects.

find . -name "node_modules" -type d -prune -print | xargs du -chs

And to actually remove them:

find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;

The article contains also instructions for windows shell.


I have added few lines inside package.json:

"scripts": {
  ...
  "clean": "rmdir /s /q node_modules",
  "reinstall": "npm run clean && npm install",
  "rebuild": "npm run clean && npm install && rmdir /s /q dist && npm run build --prod",
  ...
}

If you want to clean only you can use this rimraf node_modules or rm -rf node_modules.

It works fine


from version 6.5.0 npm supports the command clean-install to hard refresh all the packages


Have you tried npm prune?

it should uninstall everything not listed in your package file

https://npmjs.org/doc/cli/npm-prune.html


Use following command instead of npm install

npm ci

Remove/Edit the packages that are not needed in package-lock.json (package names will be written under dependencies & devDependencies) and then

npm install


First globally install rimraf

npm install rimraf -g

go to the path using cmd where your node_modules folder and apply below command

rimraf node_modules

You could remove your node_modules/ folder and then reinstall the dependencies from package.json.

rm -rf node_modules/
npm install

This would erase all installed packages in the current folder and only install the dependencies from package.json. If the dependencies have been previously installed npm will try to use the cached version, avoiding downloading the dependency a second time.


Due to its folder nesting Windows can’t delete the folder as its name is too long. To solve this, install RimRaf:

npm install rimraf -g

rimraf node_modules

For Windows User, alternative solution to remove such folder listed here: http://ask.osify.com/qa/567

Among them, a free tool: Long Path Fixer is good to try: http://corz.org/windows/software/accessories/Long-Path-Fixer-for-Windows.php


simple just run

rm -r node_modules

in fact, you can delete any folder with this.

like rm -r AnyFolderWhichIsNotDeletableFromShiftDeleteOrDelete.

just open the gitbash move to root of the folder and run this command

Hope this will help.


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to package

ModuleNotFoundError: No module named 'sklearn' Python: How to pip install opencv2 with specific version 2.4.9? Relative imports - ModuleNotFoundError: No module named x Is __init__.py not required for packages in Python 3.3+ "pip install unroll": "python setup.py egg_info" failed with error code 1 Unable to Install Any Package in Visual Studio 2015 beyond top level package error in relative import How can I specify the required Node.js version in package.json? "installation of package 'FILE_PATH' had non-zero exit status" in R Error in installation a R package

Examples related to npm

What does 'x packages are looking for funding' mean when running `npm install`? error: This is probably not a problem with npm. There is likely additional logging output above Module not found: Error: Can't resolve 'core-js/es6' Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist` ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean` What exactly is the 'react-scripts start' command? On npm install: Unhandled rejection Error: EACCES: permission denied Difference between npx and npm?