Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 805
Sergei Basharov Avatar asked Jan 14 '14 19:01

Sergei Basharov


People also ask

Can I delete node_modules folder?

Using 'Git Bash' to remove the folder is the simplest way to remove all folders including subfolders in the 'node modules'. It will take a while to delete everything, but it works without any installation.

How do I clean up node modules?

There are two ways to clean up the node_modules folder: Delete the folder and reinstall. Use npm prune (starting with npm version 6)

How do I remove unnecessary node modules?

You can use npm-prune to remove extraneous packages. Extraneous packages are packages that are not listed on the parent package's dependencies list. If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies.

What happens if I delete node_modules folder?

Anybody can suggest if I delete node_modules folder and after re-creating it, will I get all the already installed packages back in the same way they were just before deleting? YES, you will get back all the packages listed in your package. json file.


2 Answers

I think you're looking for npm prune

npm prune [<name> [<name ...]]

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

See the docs: https://docs.npmjs.com/cli/prune

like image 151
David Sherret Avatar answered Sep 19 '22 16:09

David Sherret


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.

like image 45
adamduren Avatar answered Sep 19 '22 16:09

adamduren