node.js 在 package.json 中查找未使用的 npm 包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22675725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:05:03  来源:igfitidea点击:

Find unused npm packages in package.json

node.jsdependenciesnpm

提问by Josh C

Is there a way to determine if you have packages in your package.json file that are no longer needed?

有没有办法确定 package.json 文件中是否有不再需要的包?

For instance, when trying out a package and later commenting or deleting code, but forgetting to uninstall it, I end up with a couple packages that could be deleted.

例如,当尝试一个包,然后评论或删除代码,但忘记卸载它时,我最终会得到几个可以删除的包。

What would be an efficient way to determine if a package could safely be deleted?

确定包是否可以安全删除的有效方法是什么?

回答by German Attanasio

You can use an npm module called depcheck(requires at least version 10 of Node).

您可以使用名为depcheck的 npm 模块(至少需要 Node 10 版本)。

  1. Install the module:

    npm install depcheck -g
    
    or
    
    yarn global add depcheck
    
  2. Run it and find the unused dependencies:

    depcheck
    
  1. 安装模块:

    npm install depcheck -g
    
    or
    
    yarn global add depcheck
    
  2. 运行它并找到未使用的依赖项:

    depcheck
    

The good thing about this approach is that you don't have to remember the findor grepcommand.

这种方法的好处是您不必记住findorgrep命令。

To run without installinguse npx:

要在不安装的情况下运行,请使用 npx:

npx depcheck

回答by alecxe

There is also a package called npm-check:

还有一个包叫npm-check

npm-check

Check for outdated, incorrect, and unused dependencies.

npm 检查

检查过时、不正确和未使用的依赖项。

enter image description here

在此处输入图片说明

It is quite powerful and actively developed. One of it's features it checking for unused dependencies - for this part it uses the depcheckmodule mentioned in the other answer.

它非常强大并且正在积极开发中。它的一个功能是检查未使用的依赖项 - 对于这部分,它使用depcheck另一个答案中提到的模块。

回答by fiskeben

If you're using a Unix like OS (Linux, OSX, etc) then you can use a combination of findand egrepto search for require statements containing your package name:

如果您使用的是类Unix操作系统(Linux操作系统,OSX等),那么你可以使用的组合findegrep搜索需要您的包名的语句:

find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'name-of-package' {} \;

If you search for the entire require('name-of-package')statement, remember to use the correct type of quotation marks:

如果您搜索整个require('name-of-package')语句,请记住使用正确类型的引号:

find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'require("name-of-package")' {} \;

or

或者

find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni "require('name-of-package')" {} \;

The downside is that it's not fully automatic, i.e. it doesn't extract package names from package.jsonand check them. You need to do this for each package yourself. Since package.jsonis just JSON this could be remedied by writing a small script that uses child_process.execto run this command for each dependency. And make it a module. And add it to the NPM repo...

缺点是它不是全自动的,即它不会从中提取包名称package.json并对其进行检查。您需要自己为每个包执行此操作。由于package.json只是 JSON,这可以通过编写一个小脚本来解决,该脚本child_process.exec用于为每个依赖项运行此命令。并使其成为一个模块。并将其添加到 NPM 存储库中...

回答by gombosg

fiskeben wrote:

fiskeben 写道:

The downside is that it's not fully automatic, i.e. it doesn't extract package names from package.json and check them. You need to do this for each package yourself.

缺点是它不是全自动的,即它不会从 package.json 中提取包名称并检查它们。您需要自己为每个包执行此操作。

Let's make Fiskeben's answer automated if for whatever reason depcheckis not working properly! (E.g. I tried it with Typescript and it gave unnecessary parsing errors)

如果由于某种原因depcheck无法正常工作,让我们使 Fiskeben 的回答自动化!(例如,我用 Typescript 尝试了它,但它给出了不必要的解析错误)

For parsing package.jsonwe can use the software jq. The below shell script requires a directory name where to start.

对于解析,package.json我们可以使用该软件jq。下面的 shell 脚本需要一个从哪里开始的目录名。

#!/bin/bash
DIRNAME=${1:-.}
cd $DIRNAME

FILES=$(mktemp)
PACKAGES=$(mktemp)

find . \
    -path ./node_modules -prune -or \
    -path ./build -prune -or \
    \( -name "*.ts" -or -name "*.js" -or -name "*.json" \) -print > $FILES

function check {
    cat package.json \
        | jq "{} + . | keys" \
        | sed -n 's/.*"\(.*\)".*//p' > $PACKAGES

    echo "--------------------------"
    echo "Checking ..."
    while read PACKAGE
    do
        RES=$(cat $FILES | xargs -I {} egrep -i "(import|require).*['\"]$PACKAGE[\"']" '{}' | wc -l)
        if [ $RES = 0 ]
        then
            echo -e "UNUSED\t\t $PACKAGE"
        else
            echo -e "USED ($RES)\t $PACKAGE"
        fi
    done < $PACKAGES
}

check "dependencies"
check "devDependencies"
check "peerDependencies"

First it creates two temporary files where we can cache package names and files.

首先它创建两个临时文件,我们可以在其中缓存包名和文件。

It starts with the findcommand. The first and second line make it ignore the node_modulesand buildfolders (or whatever you want). The third line contains allowed extensions, you can add more here e.g. JSX or JSON files.

它从find命令开始。第一行和第二行使它忽略node_modulesbuild文件夹(或任何你想要的)。第三行包含允许的扩展名,您可以在此处添加更多,例如 JSX 或 JSON 文件。

A function will read dependendy types.

一个函数将读取依赖类型。

First it cats the package.json. Then, jqgets the required dependency group. ({} +is there so that it won't throw an error if e.g. there are no peer dependencies in the file.)

首先catpackage.json. 然后,jq获取所需的依赖组。({} +是否存在以便在文件中没有对等依赖项时不会抛出错误。)

After that, sedextracts the parts between the quotes, the package name. -nand .../ptells it to print the matching parts and nothing else from jq's JSON output. Then we read this list of package names into a whileloop.

之后,sed提取引号之间的部分,包名称。-n.../p告诉它打印匹配的部分,而不是从jq的 JSON 输出中打印任何其他内容。然后我们将这个包名列表读入一个while循环。

RESis the number of occurrences of the package name in quotes. Right now it's import/require... 'package'/"package". It does the job for most cases.

RES是包名在引号中出现的次数。现在是import/ require... 'package'/ "package"。它在大多数情况下都能胜任。

Then we simply count the number of result lines then print the result.

然后我们简单地计算结果行的数量然后打印结果。

Caveats:

注意事项:

  • Won't find files in different imports e.g. tsconfig.jsonfiles (liboption)
  • You have to grepmanually for only ^USEDand UNUSEDfiles.
  • It's slow for large projects - shell scripts often don't scale well. But hopefully you won't be running this many times.
  • 不会在不同的导入中找到文件,例如tsconfig.json文件(lib选项)
  • 您必须grep手动仅针对^USEDUNUSED文件。
  • 对于大型项目来说速度很慢——shell 脚本通常不能很好地扩展。但希望你不会跑这么多次。

回答by user11403389

We can use the below npm module for this purpose:

为此,我们可以使用以下 npm 模块:

https://www.npmjs.com/package/npm-check-unused

https://www.npmjs.com/package/npm-check-unused

回答by transformer

many of the answer here are how to find unused items.

这里的许多答案是如何找到未使用的项目。

I wanted to remove them automatically.

我想自动删除它们

  1. Install this node project.

    $ npm install -g typescript tslint tslint-etc

  1. 安装这个节点项目。

    $ npm install -g typescript tslint tslint-etc



  1. At the root dir, add a new file tslint-imports.json

    { "extends": [ "tslint-etc" ], "rules": { "no-unused-declaration": true } }

  1. 在根目录下,添加一个新文件 tslint-imports.json

    { "extends": [ "tslint-etc" ], "rules": { "no-unused-declaration": true } }



  1. Run this at your own risk, make a backup :)

    $ tslint --config tslint-imports.json --fix --project .

  1. 自行承担风险,进行备份:)

    $ tslint --config tslint-imports.json --fix --project .