Created
April 3, 2022 18:43
-
-
Save jansroka/06a0e88d5a8a20062997961a854ade66 to your computer and use it in GitHub Desktop.
Find unused npm packages in package.json without using depcheck
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# source: https://stackoverflow.com/questions/22675725/find-unused-npm-packages-in-package-json/ | |
DIRNAME=${1:-.} | |
cd $DIRNAME | |
FILES=$(mktemp) | |
PACKAGES=$(mktemp) | |
# use fd | |
# https://github.com/sharkdp/fd | |
function check { | |
if [ ! -f "package.json" ]; then | |
echo "package.json not found, exiting..." | |
exit 1 | |
fi | |
cat package.json \ | |
| jq "{} + .$1 | keys" \ | |
| sed -n 's/.*"\(.*\)".*/\1/p' > $PACKAGES | |
echo "--------------------------" | |
echo "Checking $1..." | |
fd '(js|ts|json)$' -t f > $FILES | |
while read PACKAGE | |
do | |
if [ -d "node_modules/${PACKAGE}" ]; then | |
fd -t f '(js|ts|json)$' node_modules/${PACKAGE} >> $FILES | |
fi | |
RES=$(cat $FILES | xargs -P 32 -I {} egrep -i "(import|require|loader|plugins|${PACKAGE}).*['\"](${PACKAGE}|.?\d+)[\"']" '{}' | wc -l) | |
if [ $RES = 0 ] | |
then | |
echo -e "UNUSED\t\t $PACKAGE" | |
else | |
echo -e "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