-
Notifications
You must be signed in to change notification settings - Fork 1
/
svgx.mjs
46 lines (37 loc) · 1.13 KB
/
svgx.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
import _camelCase from 'lodash-es/camelCase.js';
import _upperFirst from 'lodash-es/upperFirst.js';
import { getFilenameParts } from './parse-filename.mjs';
const nonWords = /[\W$]/;
/**
* Read an SVG file (which is text) and build a react component that returns the SVG.
*/
export async function load(url, ctx, next) {
const { ext, ...others } = getFilenameParts(url);
const base = pascalCase(others.base);
if (ext !== '.svg') return next(url);
if (nonWords.test(base)) {
throw new SyntaxError([
'Cannot generate a react component name from filename',
`"${base}"`,
'as it contains character(s) illegal for JavaScript identifiers',
].join(' '));
}
const source = `export default function ${base}() { return (\n${(await next(url, { format: 'jsx' })).source}); }`;
return {
...ctx,
format: 'module',
source,
};
}
/**
* Convert a string to quasi-PascalCase.
* @param {string} input The string to transform.
* @returns {string} The transformed string.
*
* @example
* foo-bar → FooBar
* i/o stream → IOStream
*/
function pascalCase(input) {
return _upperFirst(_camelCase(input));
}