DEV Community

Jeremy Gollehon
Jeremy Gollehon

Posted on

Automatically Remove Unused Node Modules with Python

We keep a directory under the root of our projects called _dev_tools.

It consists of Python scripts we can quickly run, usually by pressing the Play button of the Code Runner extension in VS Code, to help with project management.

The key is creating tools that work cross-platform on Windows, Mac, and Linux.

Here's our script for removing unused node modules.

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")
Enter fullscreen mode Exit fullscreen mode

Discussion (0)