Skip to content

Instantly share code, notes, and snippets.

@Boshen
Last active April 17, 2024 05:50
Show Gist options
  • Save Boshen/2cbac159cbc989ee714ca07d07825e75 to your computer and use it in GitHub Desktop.
Save Boshen/2cbac159cbc989ee714ca07d07825e75 to your computer and use it in GitHub Desktop.
npm machette - find unused dependencies by grepping the dependency name
// pnpm -r -c exec 'node /path/to/machette.js'
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const process = require('process');
const path = require('path');
async function main() {
const cwd = process.cwd();
const packageJsonPath = path.join(cwd, "package.json");
const packageJson = require(packageJsonPath);
if (packageJson.dependencies === undefined) {
return
}
const deps = Object.keys(packageJson.dependencies);
const scripts = packageJson.scripts || {};
const results = [];
const tasks = deps
.filter((dep) => !dep.startsWith('@types'))
.filter((dep) => !Object.values(scripts).some((s) => s.includes(dep)))
.map(async (dep) => {
try {
const { stdout } = await exec(`git grep ${dep} | grep -e import -e require`, {maxBuffer: 1024 * 1000})
if (stdout.length === 0) {
results.push(dep);
}
} catch (e) {
results.push(dep);
}
});
await Promise.all(tasks);
if (results.length > 0) {
console.log('-------------')
console.log('cwd:', cwd);
console.log(results)
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment