To remove packages in the node_modules folder that are not defined in the package.json file, several methods can be used. Here are two common approaches to solve this issue:
Using the npm prune command
npm provides an internal command prune that removes packages in the node_modules directory not declared in the dependencies or devDependencies section of the package.json file. To use npm prune, simply open a terminal in the project's root directory and execute the following command:
bashnpm prune
This command will remove all packages that do not match the dependencies specified in the current package.json file.
Manual Cleanup and Reinstallation
If you want to ensure that the node_modules folder fully reflects the dependencies listed in the package.json file, you can manually delete the node_modules folder and then run npm install to reinstall all dependencies. Here are the steps:
-
Delete the
node_modulesfolder:bashrm -rf node_modules -
Clean the npm cache (optional):
bashnpm cache clean --force -
Reinstall dependencies using
npm install:bashnpm install
This will create a new node_modules folder containing only the dependencies declared in the package.json file.
Real-World Example
Suppose I previously installed a package named example-package temporarily for testing certain features, but later found it unsuitable for my project needs, so I did not add it to the package.json file. Now, my node_modules folder contains many such packages, and I want to clean them up. I would do the following:
- Open a terminal and navigate to my project directory.
- Run the
npm prunecommand. - npm will check the
package.jsonfile and automatically remove all packages not listed, includingexample-package.
This way, the node_modules folder only contains the necessary dependencies, making my project cleaner and easier to maintain.