Skip to content

Instantly share code, notes, and snippets.

@glebcha
Last active April 25, 2023 10:11
Show Gist options
  • Save glebcha/d104b40b3b5c5822736ef88da3591a5a to your computer and use it in GitHub Desktop.
Save glebcha/d104b40b3b5c5822736ef88da3591a5a to your computer and use it in GitHub Desktop.
Find unused packages from package.json
#!/bin/bash
# Enhanced version of https://stackoverflow.com/a/52371112/1835055
DIRNAME=${1:-.}
cd $DIRNAME
FILES=$(mktemp)
PACKAGES=$(mktemp)
find . \
-path ./node_modules -prune -or \
-path ./build -prune -or \
\( -name "*.ts" -or -name "*.tsx" -or -name "*.js" -or -name "*.json" \) -print > $FILES
function check {
cat package.json \
| jq "{} + .$1 | keys" \
| sed -n 's/.*"\(.*\)".*/\1/p' > $PACKAGES
echo "--------------------------"
echo "Checking $1..."
while read PACKAGE
do
RES=$(cat $FILES | xargs -P 64 -I {} egrep -i "(import|require|loader|plugins|$PACKAGE).*['\"]($PACKAGE.*|.?\d+)[\"']" '{}' | wc -l)
if [ $RES = 0 ]
then
echo "UNUSED\t\t $PACKAGE"
else
echo "USED ($RES)\t $PACKAGE"
fi
done < $PACKAGES
}
check "dependencies"
check "devDependencies"
check "peerDependencies"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment