/
purgecss.js
executable file
·90 lines (81 loc) · 2.61 KB
/
purgecss.js
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
#!/usr/bin/env node
const program = require("commander");
const fs = require("fs");
const {
default: PurgeCSS,
defaultOptions,
setOptions,
} = require("../lib/purgecss");
function getList(list) {
return list.split(",");
}
async function writeCSSToFile(filePath, css) {
try {
await fs.promises.writeFile(filePath, css);
} catch (err) {
console.error(err.message);
}
}
program
.usage("--css <css> --content <content> [options]")
.option(
"-con, --content <files>",
"glob of content files (comma separated)",
getList
)
.option("-css, --css <files>", "glob of css files (comma separated)", getList)
.option("-c, --config <path>", "path to the configuration file")
.option(
"-o, --output <path>",
"file path directory to write purged css files to"
)
.option("-font, --font-face", "option to remove unused font-faces")
.option("-keyframes, --keyframes", "option to remove unused keyframes")
.option("-rejected, --rejected", "option to output rejected selectors")
.option(
"-s, --safellist <list>",
"list of classes that should not be removed (comma separated)",
getList
)
.option(
"-b, --blocklist <list>",
"list of selectors that should be removed",
getList
);
program.parse(process.argv);
// config file is not specified or the content and css are not,
// PurgeCSS will not run
if (!program.config && !(program.content && program.css)) {
program.help();
}
(async () => {
// if the config file is present, use it
// other options specified will override
let options = defaultOptions;
if (program.config) {
options = await setOptions(program.config);
}
if (program.content) options.content = program.content;
if (program.css) options.css = program.css;
if (program.fontFace) options.fontFace = program.fontFace;
if (program.keyframes) options.keyframes = program.keyframes;
if (program.rejected) options.rejected = program.rejected;
if (program.variables) options.variables = program.variables;
if (program.safelist) options.safelist = program.safelist;
if (program.blocklist) options.blocklist = program.blocklist;
const purged = await new PurgeCSS().purge(options);
const output = options.output || program.output;
// output results in specified directory
if (output) {
if (purged.length === 1 && output.endsWith(".css")) {
await writeCSSToFile(output, purged[0].css);
return;
}
for (const purgedResult of purged) {
const fileName = purgedResult.file.split("/").pop();
await writeCSSToFile(`${output}/${fileName}`, purgedResult.css);
}
} else {
console.log(JSON.stringify(purged));
}
})();