-
-
Notifications
You must be signed in to change notification settings - Fork 245
/
Copy pathindex.ts
108 lines (100 loc) · 3.09 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import * as glob from "glob";
import PluginError from "plugin-error";
import { PurgeCSS } from "purgecss";
import * as internal from "stream";
import through from "through2";
import VinylFile from "vinyl";
import applySourceMap from "vinyl-sourcemaps-apply";
import { UserDefinedOptions } from "./types";
export { UserDefinedOptions };
const PLUGIN_NAME = "gulp-purgecss";
function getFiles(contentArray: string[], ignore?: string[]): string[] {
return contentArray.reduce((acc: string[], content) => {
return [...acc, ...glob.sync(content, { ignore })];
}, []);
}
/**
*
* @param options - options
* @returns
*
* @public
*/
function gulpPurgeCSS(options: UserDefinedOptions): internal.Transform {
return through.obj(async function (file: VinylFile, _encoding, callback) {
// empty
if (file.isNull()) return callback(null, file);
// buffer
if (file.isBuffer()) {
try {
const optionsGulp = {
...options,
content: getFiles(options.content, options.skippedContentGlobs),
css: [
{
raw: file.contents.toString(),
},
],
stdin: true,
sourceMap: !!file.sourceMap,
};
const purgedCSSResults = await new PurgeCSS().purge(optionsGulp);
const purge = purgedCSSResults[0];
const result =
optionsGulp.rejected && purge.rejected
? purge.rejected.join(" {}\n") + " {}"
: purge.css;
file.contents = Buffer.from(result, "utf-8");
// apply source map to the chain
if (file.sourceMap) {
applySourceMap(file, purge.sourceMap);
}
callback(null, file);
} catch (e: unknown) {
if (e instanceof Error) {
this.emit("error", new PluginError(PLUGIN_NAME, e.message));
}
}
}
// stream
if (file.isStream()) {
let css = "";
file.contents
.on("data", (buffer: string | Buffer) => {
css += buffer.toString();
})
.on("end", async () => {
try {
const optionsGulp = {
...options,
css: [
{
raw: css,
},
],
sourceMap: !!file.sourceMap,
};
const purgedCSSResults = await new PurgeCSS().purge(optionsGulp);
const purge = purgedCSSResults[0];
const result =
optionsGulp.rejected && purge.rejected
? purge.rejected.join(" {}\n") + " {}"
: purge.css;
const streamResult = through();
streamResult.write(Buffer.from(result, "utf-8"));
file.contents = file.contents.pipe(streamResult);
// apply source map to the chain
if (file.sourceMap) {
applySourceMap(file, purge.sourceMap);
}
callback(null, file);
} catch (e: unknown) {
if (e instanceof Error) {
this.emit("error", new PluginError(PLUGIN_NAME, e.message));
}
}
});
}
});
}
export default gulpPurgeCSS;