TheGabornator
TheGabornator

Reputation: 551

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. It gives me a ton of false alerts aparts from having to configure it for "config-only" libs like babel, eslint etc.

What is your approach if you get a task like it? Is there any best practice you could recommend me?

Thank you!

Upvotes: 17

Views: 15265

Answers (2)

GollyJer
GollyJer

Reputation: 26752

We use depcheck with Python to isolate the package.json dependencies key.

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")

Upvotes: 2

Mestre San
Mestre San

Reputation: 1925

The answer is 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

Upvotes: 8

Related Questions