This repository has been archived by the owner on Dec 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
54 lines (50 loc) · 1.47 KB
/
index.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
const fs = require("fs");
const { optimize } = require("svgo");
const svelte = require("svelte/compiler");
function compileSvg(source, filename, ssr) {
const {
js: { code },
} = svelte.compile(source, {
generate: ssr ? "ssr" : "dom",
dev: process.env.NODE_ENV === "development",
hydratable: true,
});
return { code };
}
function optimizeSvg(content, path, config = {}) {
const { data } = optimize(content, {
...config,
path,
});
return data;
}
module.exports = (options = {}) => {
const { svgoConfig } = options;
const svgRegex = /\.svg(?:\?(component))?$/;
const splitRegex = /(<svg.*?)(\/?>.*)/;
return {
name: "svelte-svg",
transform(_, id, ssr) {
const result = id.match(svgRegex);
if (result) {
const type = result[1];
if (type === "component") {
const idWithoutQuery = id.replace(".svg?component", ".svg");
const code = fs.readFileSync(idWithoutQuery);
let svg = optimizeSvg(code, idWithoutQuery, svgoConfig);
// Support any custom attributes
const parts = splitRegex.exec(svg);
if (parts === null) {
console.error("[vite-plugin-svelte-svg] Failed to parse:", idWithoutQuery);
} else {
const [_, head, body] = parts;
svg = `${head} {...$$props}${body}`;
}
// Compile with Svelte
return compileSvg(svg, idWithoutQuery, ssr);
}
}
return null;
},
};
};