-
Notifications
You must be signed in to change notification settings - Fork 1
/
filter-npm-deps.mjs
73 lines (59 loc) · 1.8 KB
/
filter-npm-deps.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
#!/usr/bin/env node
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { parseArgs } from 'node:util';
import { log } from 'node:console';
import { cwd, exit } from 'node:process';
const {
values: { deps, help },
} = parseArgs({
options: {
deps: {
short: 'd',
type: 'string',
},
help: {
type: 'boolean',
short: 'h',
},
},
});
const dependenciesToKeep = deps?.split(',') ?? [];
if (dependenciesToKeep.length === 0 || help) {
log(`Usage: filter-npm-deps [options]
Options:
-h, --help Show this help message and exit.
-d, --deps A list of comma-separated NPM packages to filter for within package.json`);
exit(0);
}
const packageJsonFileName = 'package.json';
const currentPath = cwd();
if (!existsSync(packageJsonFileName)) {
throw new Error(
`Couldn't find a package.json in ${currentPath}.
Please make sure you run the command in a directory containing a package.json file.`,
);
}
let packageJSON
try {
packageJSON = JSON.parse(readFileSync(packageJsonFileName, 'utf8'));
} catch (error) {
throw new Error(
`Could not parse the content of package.json in ${currentPath}.
Error: ${error}`,
);
}
const filterDeps = (object) =>
Object.fromEntries(
Object.entries(object ?? {}).filter(([key]) =>
dependenciesToKeep.includes(key),
),
);
for(const dependencyField of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
if(packageJSON[dependencyField]) {
packageJSON[dependencyField] = filterDeps(packageJSON[dependencyField])
}
}
if(packageJSON.bundleDependencies) {
packageJSON.bundleDependencies = packageJSON.bundleDependencies.filter(dependency => dependenciesToKeep.includes(dependency))
}
writeFileSync(packageJsonFileName, JSON.stringify(packageJSON), 'utf8');