/
index.ts
80 lines (71 loc) · 1.78 KB
/
index.ts
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
import * as fs from "fs";
import { PurgeCSS } from "purgecss";
import { Plugin } from "rollup";
import { createFilter } from "rollup-pluginutils";
import { UserDefinedOptions } from "./types";
export * from "./types";
/**
*
* @param options - options
* @returns
*
* @public
*/
function pluginPurgeCSS(options: UserDefinedOptions): Plugin {
const filter = createFilter(
options.include || ["**/*.css"],
options.exclude || "node_modules/**"
);
const styles: string[] = [];
let dest = "";
return {
name: "purgecss",
transform: async (code, id) => {
if (!filter(id)) return null;
const v = await new PurgeCSS().purge({
content: options.content,
css: [
{
raw: code,
},
],
});
let css = v[0].css;
styles.push(css);
css = JSON.stringify(css);
if (options.insert) {
// do thing
} else if (!options.output) {
code = css;
} else {
code = `"";`;
}
return {
code: `export default ${code}`,
map: { mappings: "" },
};
},
generateBundle() {
if (!options.insert && (!styles.length || options.output === false)) {
return;
}
const css = styles.reduce((acc, value) => {
return acc + value;
}, "");
if (typeof options.output === "string") {
return fs.writeFileSync(options.output, css);
}
if (typeof options.output === "function") {
return options.output(css, styles);
}
if (!options.insert && dest) {
if (dest.endsWith(".js") || dest.endsWith(".ts")) {
dest = dest.slice(0, -3);
}
dest = `${dest}.css`;
return fs.writeFileSync(dest, css);
}
},
};
}
export default pluginPurgeCSS;