Skip to content

Commit 91027f6

Browse files
committed
Initial commit
0 parents  commit 91027f6

File tree

5 files changed

+264
-0
lines changed

5 files changed

+264
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

.prettierrc

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"singleQuote": true,
3+
"printWidth": 120,
4+
"arrowParens": "avoid",
5+
"semi": true,
6+
"tabWidth": 2,
7+
"useTabs": false,
8+
"trailingComma": "es5"
9+
}

index.js

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
const { getOptions } = require('loader-utils');
2+
const { optimize } = require('svgo');
3+
const svelte = require('svelte/compiler');
4+
5+
module.exports.default = function loader(source) {
6+
const { resourcePath } = this;
7+
const { svgoConfig, ssr } = getOptions(this) || {};
8+
const splitRegex = /(<svg.*?)(\/?>.*)/;
9+
const code = source.toString();
10+
11+
let svg = optimizeSvg(code, resourcePath, svgoConfig);
12+
// Support any custom attributes
13+
const parts = splitRegex.exec(svg);
14+
if (parts === null) {
15+
console.error('[svelte-svg-loader] Failed to parse:', resourcePath);
16+
} else {
17+
const [_, head, body] = parts;
18+
svg = `${head} {...$$props}${body}`;
19+
}
20+
21+
// Compile with Svelte
22+
return compileSvg(svg, resourcePath, ssr).code;
23+
};
24+
25+
function compileSvg(source, filename, ssr) {
26+
const {
27+
js: { code, map },
28+
} = svelte.compile(source, {
29+
generate: ssr ? 'ssr' : 'dom',
30+
// If `dev` is set to true, trying to instantiate the component from Webpack will throw a "'target' is a required option" error.
31+
dev: false,
32+
hydratable: true,
33+
});
34+
return { code, map };
35+
}
36+
37+
function optimizeSvg(content, path, config = {}) {
38+
const { data } = optimize(content, {
39+
...config,
40+
path,
41+
});
42+
return data;
43+
}

package.json

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "svelte-svg-loader",
3+
"version": "1.0.0",
4+
"description": "Webpack loader to load SVG files as Svelte components",
5+
"main": "index.js",
6+
"author": "Metafy <[email protected]>",
7+
"license": "MIT",
8+
"devDependencies": {
9+
"svelte": "^3.38.3"
10+
},
11+
"dependencies": {
12+
"loader-utils": "^2.0.0",
13+
"svgo": "^2.3.0"
14+
}
15+
}

pnpm-lock.yaml

+196
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)