简体   繁体   English

如何从 package.json 中删除冗余/未使用的依赖项?

[英]How to remove redundant/unused dependencies from package.json?

I know it has been asked before, but depcheck doesn't seem to work for me at all.我知道之前有人问过它,但是depcheck似乎根本不适合我。 It gives me a ton of false alerts aparts from having to configure it for "config-only" libs like babel, eslint etc.除了必须为 babel、eslint 等“仅配置”库配置它之外,它还给了我大量的错误警报。

What is your approach if you get a task like it?如果你接到这样的任务,你的方法是什么? Is there any best practice you could recommend me?你有什么最佳实践可以推荐给我吗?

Thank you!谢谢!

The answer is npm-check .答案是npm-check

npm i -g npm-check

Then enter the directory of you project and run the tool然后进入你的项目目录并运行该工具

cd my-app
npm-check


some-package 😕  NOTUSED?
             To remove this package: npm uninstall --save some-package

We use depcheck with Python to isolate the package.json dependencies key.我们使用depcheck和 Python 来隔离 package.json dependencies项键。

import json
from sys import platform
from subprocess import run

div = "=================================="
use_shell = platform == "win32"

print(f"\nFinding unused dependencies\n{div}\n")

cmd = ["npx", "depcheck", "--json"]
depcheck_result = run(cmd, shell=use_shell, capture_output=True, text=True)

unused_dependencies = json.loads(depcheck_result.stdout)["dependencies"]
if len(unused_dependencies) > 0:
    print(f"Found these unused dependencies\n{div}")
    print(*unused_dependencies, sep="\n")

    affirmative_responses = {"y", "yes", "Y", "YES", ""}
    response = input(f"{div}\n\nRemove all? [yes] ").lower() in affirmative_responses

    if response == True:
        cmd = ["yarn", "remove", *unused_dependencies]
        run(cmd, shell=use_shell)

    print(f"\nDone!\n{div}\n")

else:
    print(f"\nDone! - No unused dependencies found.\n{div}\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM