-
Notifications
You must be signed in to change notification settings - Fork 1
/
icons-plugin.mjs
66 lines (48 loc) · 1.33 KB
/
icons-plugin.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
import got from "got";
import valueParser from "postcss-value-parser";
import { transform, encode } from "postcss-inline-svg/lib/defaults.js";
const map = new Map();
const FUNCTION_NAME = "icon";
const requireIconSvg = (iconId) => {
return new Promise((resolve) => {
got(`https://fonts.gstatic.com/s/i/materialicons/${iconId}/24px.svg?download=true`, {
cache: map,
}).then((response) => {
resolve(response.body);
});
});
};
const plugin = () => ({
postcssPlugin: "icons",
async Declaration(decl) {
let value = decl.value;
if (value.indexOf(FUNCTION_NAME) === -1) {
return;
}
const parsed = valueParser(value);
const [functionNode] = parsed.nodes;
if (functionNode.type !== "function") {
return;
}
if (functionNode.value !== FUNCTION_NAME) {
return;
}
const [iconIdNode] = functionNode.nodes;
if (iconIdNode.type !== "string") {
throw new Error(`Invalid decl ${value}`);
}
const iconId = iconIdNode.value;
const svg = await requireIconSvg(iconId);
const dataUri = transform(encode(svg));
functionNode.value = "url";
functionNode.nodes = [
{
type: "word",
value: dataUri,
},
];
decl.value = parsed.toString();
},
});
export const postcss = true;
export default plugin;