Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active May 10, 2022 11:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ccnokes/2b80dcfd870d3412b58bc96b8c5b84d7 to your computer and use it in GitHub Desktop.
Save ccnokes/2b80dcfd870d3412b58bc96b8c5b84d7 to your computer and use it in GitHub Desktop.
Bash script to grep for unused dependencies in a node.js project
set -e
# function to grep for a dependency
grep_dep() {
# params: $1 = the string to grep for, $2 = directory to grep in
# [1]
grep --include="*.js" --exclude-dir="node_modules" -R --color -n "require\(.*$1.*\)" "$2"
# if grep returns 0 results, it has an exit code of 1. No results means dependency is not in use
if [[ $? > 0 ]]; then
echo
echo "** No uses of $1 found, consider removing. **"
echo
fi
}
# [2]
export -f grep_dep
# [3]
jq -r '.dependencies | keys | .[]' package.json | \
# [4]
xargs -I '{}' -P 4 -t bash -c "grep_dep '{}' ."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment