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

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

5 个月前提问
3 个月前修改
浏览次数148

6个答案

1
2
3
4
5
6

要清除 node_modules 文件夹中没有在 package.json 中定义的包,可以使用几种方法。以下是解决这个问题的两种常见方式:

使用 npm prune 命令

npm 提供了一个内置的命令 prune,它用于移除 node_modules 目录中未在 package.json 文件的 dependenciesdevDependencies 中声明的包。要使用 npm prune,您只需要在项目的根目录下打开终端,并执行以下命令:

bash
npm prune

这条命令会根据当前 package.json 文件中定义的依赖项,删除所有不匹配的包。

手动清理和重新安装

如果想确保 node_modules 文件夹完全反映 package.json 文件中指定的依赖关系,您可以先手动删除 node_modules 文件夹,然后运行 npm install 重新安装所有依赖。以下是这个方法的步骤:

  1. 删除 node_modules 文件夹:

    bash
    rm -rf node_modules
  2. 清理 npm 缓存(可选):

    bash
    npm cache clean --force
  3. 使用 npm install 重新安装依赖:

    bash
    npm install

这将创建一个新的 node_modules 文件夹,其中仅包含 package.json 文件中声明的依赖包。

实际例子

假设我之前为了测试某些功能,临时安装了一个名为 example-package 的包,但后来发现它并不适合我的项目需求,所以我没有将它加入到 package.json 中。现在我的 node_modules 文件夹里有很多这样的包,我想清理它们。我会这样做:

  1. 打开终端并导航到我的项目目录。
  2. 运行 npm prune 命令。
  3. npm 会检查 package.json 并自动移除所有未列出的包,包括 example-package

这样,node_modules 文件夹就只包含了真正需要的依赖,我的项目也就更加整洁、更容易维护。

2024年6月29日 12:07 回复

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

2024年6月29日 12:07 回复

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

shell
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.

2024年6月29日 12:07 回复

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

shell
npm install rimraf -g rimraf node_modules
2024年6月29日 12:07 回复

simple just run

shell
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.

2024年6月29日 12:07 回复

你的答案