-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfind-unused-exports.mjs
executable file
·100 lines (81 loc) · 2.83 KB
/
find-unused-exports.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/usr/bin/env node
// @ts-check
/** @import { ImportMap } from "@import-maps/resolve" */
import { relative } from "node:path";
import arg from "arg";
import { bold, dim, green, red, underline } from "kleur/colors";
import CliError from "./CliError.mjs";
import errorConsole from "./errorConsole.mjs";
import findUnusedExports from "./findUnusedExports.mjs";
import reportCliError from "./reportCliError.mjs";
/**
* Runs the `find-unused-exports` CLI.
* @returns {Promise<void>} Resolves once the operation is done.
*/
async function findUnusedExportsCli() {
try {
const {
"--import-map": importMapJson,
"--module-glob": moduleGlob,
"--resolve-file-extensions": resolveFileExtensionsList,
"--resolve-index-files": resolveIndexFiles,
} = arg({
"--import-map": String,
"--module-glob": String,
"--resolve-file-extensions": String,
"--resolve-index-files": Boolean,
});
/** @type {ImportMap | undefined} */
let importMap;
if (importMapJson) {
try {
importMap = JSON.parse(importMapJson);
} catch {
throw new CliError(`The \`--import-map\` argument must be JSON.`);
}
}
if (resolveIndexFiles && !resolveFileExtensionsList)
throw new CliError(
"The `--resolve-index-files` flag can only be used with the `--resolve-file-extensions` argument.",
);
const unusedExports = await findUnusedExports({
importMap,
moduleGlob,
resolveFileExtensions: resolveFileExtensionsList
? resolveFileExtensionsList.split(",")
: undefined,
resolveIndexFiles,
});
// Sort the list so that the results will be deterministic (important for
// snapshot tests) and tidy (for output readability).
const unusedExportsModulePaths = Object.keys(unusedExports).sort();
const countUnusedExportsModules = unusedExportsModulePaths.length;
let countUnusedExports = 0;
if (countUnusedExportsModules) {
const cwd = process.cwd();
for (const path of unusedExportsModulePaths) {
const exports = unusedExports[path];
countUnusedExports += exports.size;
errorConsole.group(`\n${underline(red(relative(cwd, path)))}`);
errorConsole.error(dim(red(Array.from(exports).join(", "))));
errorConsole.groupEnd();
}
errorConsole.error(
`\n${bold(
red(
`${countUnusedExports} unused export${
countUnusedExports === 1 ? "" : "s"
} in ${countUnusedExportsModules} module${
countUnusedExportsModules === 1 ? "" : "s"
}.`,
),
)}\n`,
);
process.exitCode = 1;
} else console.info(`\n${bold(green(`0 unused exports.`))}\n`);
} catch (error) {
reportCliError("find-unused-exports", error);
process.exitCode = 1;
}
}
findUnusedExportsCli();