-
-
Save DarkGL/e808ac64b5fcae705fb7a32edeac1ec0 to your computer and use it in GitHub Desktop.
npm machette - find unused dependencies by grepping the dependency name
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
// 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