@reliverse/rse
Version:
@reliverse/rse is your all-in-one companion for bootstrapping and improving any kind of projects (especially web apps built with frameworks like Next.js) — whether you're kicking off something new or upgrading an existing app. It is also a little AI-power
32 lines (31 loc) • 1.14 kB
JavaScript
import path from "@reliverse/pathkit";
import fs from "@reliverse/relifso";
import { destr } from "destr";
import { glob } from "tinyglobby";
export async function getUnusedDependencies(cwd, ignoredDeps = []) {
const packageJsonPath = path.join(cwd, "package.json");
const packageJson = destr(
await fs.readFile(packageJsonPath, "utf-8")
);
const allDeps = {
...packageJson.dependencies ?? {},
...packageJson.devDependencies ?? {}
};
const files = await glob("**/*.{js,jsx,ts,tsx}", { cwd });
const imports = /* @__PURE__ */ new Set();
for (const file of files) {
const content = await fs.readFile(path.join(cwd, file), "utf-8");
const importMatches = content.matchAll(/from ['"]([^'"]+)['"]/g);
for (const match of importMatches) {
const [, pkg] = match;
if (pkg && !pkg.startsWith(".") && !pkg.startsWith("~/")) {
imports.add(pkg.split("/")[0]);
}
}
}
return Object.keys(allDeps).filter(
(dep) => !imports.has(dep) && !ignoredDeps.some(
(pattern) => pattern.startsWith("/") ? new RegExp(pattern.slice(1, -1)).test(dep) : pattern === dep
)
);
}