-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
43 lines (38 loc) · 1.2 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
const { getOptions } = require('loader-utils');
const { optimize } = require('svgo');
const svelte = require('svelte/compiler');
module.exports.default = function loader(source) {
const { resourcePath } = this;
const { svgoConfig, ssr } = getOptions(this) || {};
const splitRegex = /(<svg.*?)(\/?>.*)/;
const code = source.toString();
let svg = optimizeSvg(code, resourcePath, svgoConfig);
// Support any custom attributes
const parts = splitRegex.exec(svg);
if (parts === null) {
console.error('[svelte-svg-loader] Failed to parse:', resourcePath);
} else {
const [_, head, body] = parts;
svg = `${head} {...$$props}${body}`;
}
// Compile with Svelte
return compileSvg(svg, resourcePath, ssr).code;
};
function compileSvg(source, filename, ssr) {
const {
js: { code, map },
} = svelte.compile(source, {
generate: ssr ? 'ssr' : 'dom',
// If `dev` is set to true, trying to instantiate the component from Webpack will throw a "'target' is a required option" error.
dev: false,
hydratable: true,
});
return { code, map };
}
function optimizeSvg(content, path, config = {}) {
const { data } = optimize(content, {
...config,
path,
});
return data;
}