乐闻世界logo
搜索文章和话题

How to clean node_modules folder of packages that are not in package. Json ?

1个答案

1

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:

bash
npm 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:

  1. Delete the node_modules folder:

    bash
    rm -rf node_modules
  2. Clean the npm cache (optional):

    bash
    npm cache clean --force
  3. Reinstall dependencies using npm install:

    bash
    npm 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:

  1. Open a terminal and navigate to my project directory.
  2. Run the npm prune command.
  3. npm will check the package.json file and automatically remove all packages not listed, including example-package.

This way, the node_modules folder only contains the necessary dependencies, making my project cleaner and easier to maintain.

2024年6月29日 12:07 回复

你的答案