-
Notifications
You must be signed in to change notification settings - Fork 67
/
svgmin.mjs
58 lines (49 loc) · 1.4 KB
/
svgmin.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
import { readFile } from "node:fs/promises";
import { optimize } from "svgo";
// based on https://github.com/withastro/roadmap/discussions/667#discussioncomment-6926854
const EXPORTS_DEFAULT = "export default ";
/**
* @returns {import('vite').Plugin}
*/
export function svgr() {
return {
enforce: "pre",
name: "astro:svga",
async transform(code, id) {
if (!id.endsWith(".svg?react")) {
return null;
}
let idx = id;
let codex = code;
// remove the annoying querystring
idx = id.replace(/\?react$/, "");
// this is because the `@astrojs/image` transforms the file already
// and replaces with the url to load instead of the real source
if (code.startsWith(EXPORTS_DEFAULT)) {
codex = code.replace(EXPORTS_DEFAULT, "");
codex = await readFile(idx, "utf-8");
}
// optimize the svg
codex = optimize(codex).data;
const resolved = `const SVG = ${JSON.stringify(codex)};
export default SVG;
if (import.meta.hot) import.meta.hot.decline();`;
return {
code: resolved,
meta: {
astro: {
hydratedComponents: [],
clientOnlyComponents: [],
scripts: [],
propagation: "none",
containsHead: false,
pageOptions: {},
},
vite: {
lang: "ts",
},
},
};
},
};
}