#!/bin/bash
DIRNAME=${1:-.}
cd $DIRNAME
FILES=$(mktemp)
PACKAGES=$(mktemp)
# use fd
# https://github.com/sharkdp/fd
function check {
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 -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"
与原始脚本的结果:
--------------------------
Checking dependencies...
UNUSED jquery
--------------------------
Checking devDependencies...
UNUSED @types/jquery
UNUSED @types/jqueryui
USED (1) autoprefixer
USED (1) awesome-typescript-loader
USED (1) cache-loader
USED (1) css-loader
USED (1) d3
USED (1) mini-css-extract-plugin
USED (1) postcss-loader
UNUSED sass
USED (1) sass-loader
USED (1) terser-webpack-plugin
UNUSED typescript
UNUSED webpack
UNUSED webpack-cli
USED (1) webpack-fix-style-only-entries
修改后:
Checking dependencies...
USED (5) jquery
--------------------------
Checking devDependencies...
UNUSED @types/jquery
UNUSED @types/jqueryui
USED (1) autoprefixer
USED (1) awesome-typescript-loader
USED (1) cache-loader
USED (1) css-loader
USED (2) d3
USED (1) mini-css-extract-plugin
USED (1) postcss-loader
USED (3) sass
USED (1) sass-loader
USED (1) terser-webpack-plugin
USED (16) typescript
USED (16) webpack
USED (2) webpack-cli
USED (2) webpack-fix-style-only-entries
const check = require("unused-package");
check({ entries: ['entry path to your code'] }).then((res) => {
console.log(res) // list of packages returned by library
});