【问题标题】:How to remove redundant/unused dependencies from package.json?如何从 package.json 中删除冗余/未使用的依赖项?
【发布时间】:2019-08-01 21:31:39
【问题描述】:

我知道以前有人问过这个问题,但depcheck 似乎根本不适合我。除了必须为 babel、eslint 等“仅配置”库配置它之外,它给了我大量的错误警报。

如果你接到这样的任务,你的方法是什么?有什么最佳做法可以推荐给我吗?

谢谢!

【问题讨论】:

  • 你试过yarn autoclean吗?
  • 感谢您的提示。看起来它只从 ​​node_modules 中删除了冗余文件。我正在寻找的是从我的 package.json 中删除那些的东西,或者至少列出了没有在任何地方使用的 deps。
  • 可能是最可靠的方法是删除 node_modules 运行应用程序并根据需要慢慢添加deps,直到应用程序运行。我只想说跟踪使用的版本,因为您不想引入任何重大更改。
  • 很公平。我希望有一位资深的 javascript 向导看到这个,谁能给我一个银弹:)
  • 如果它不存在,这是一个很酷的开发工具;)

标签: javascript node.js reactjs npm yarnpkg


【解决方案1】:

我们使用 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")

【讨论】:

    【解决方案2】:

    答案是npm-check

    npm i -g npm-check
    

    然后进入你的项目目录并运行工具

    cd my-app
    npm-check
    
    
    some-package ?  NOTUSED?
                 To remove this package: npm uninstall --save some-package
    

    【讨论】:

      猜你喜欢
      • 2013-10-25
      • 2020-12-07
      • 2023-02-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 2019-12-03
      • 2015-10-20
      相关资源
      最近更新 更多