Skip to content

Commit dc54f91

Browse files
committed
🛠️ Refactor parseReactSvgContent to improve SVG handling and formatting
1 parent dd503d4 commit dc54f91

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

src/utils/parseReactSvgContent.ts

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,46 @@
1-
import { parse, print, type Module } from "@swc/core";
1+
import prettier from "prettier";
22

33
interface ParseReactSvgOptions {
44
componentName: string;
55
svgCode: string;
66
typescript: boolean;
7-
minify?: boolean;
87
}
98

109
export const parseReactSvgContent = async ({
1110
componentName,
1211
svgCode,
1312
typescript,
14-
minify = false,
1513
}: ParseReactSvgOptions) => {
16-
let structuredCode = "";
14+
const reactifiedSvg = svgCode
15+
.replace("<svg", "<svg {...props}")
16+
.replace(/class="/g, 'className="')
17+
.replace(/clip-rule="/g, 'clipRule="')
18+
.replace(/fill-rule="/g, 'fillRule="')
19+
.replace(/stroke-width="/g, 'strokeWidth="')
20+
.replace(/stroke-linecap="/g, 'strokeLinecap="')
21+
.replace(/stroke-linejoin="/g, 'strokeLinejoin="')
22+
.replace(/stroke-dasharray="/g, 'strokeDasharray="')
23+
.replace(/stroke-dashoffset="/g, 'strokeDashoffset="')
24+
.replace(/stroke-miterlimit="/g, 'strokeMiterlimit="')
25+
.replace(/text-anchor="/g, 'textAnchor="')
26+
.replace(/xml:space="/g, 'xmlSpace="');
1727

28+
let structuredCode = "";
1829
if (typescript) {
1930
structuredCode =
2031
`import * as React from 'react';\n\n` +
21-
`const ${componentName} = (props: React.SVGProps<SVGSVGElement>) => (\n ${svgCode.replace("<svg", "<svg {...props}")}\n);\n\n` +
32+
`const ${componentName} = (props: React.SVGProps<SVGSVGElement>) => (\n ${reactifiedSvg}\n);\n\n` +
2233
`export { ${componentName} };`;
2334
} else {
24-
structuredCode = `const ${componentName} = (props) => (\n ${svgCode.replace("<svg", "<svg {...props}")}\n);\n\nexport { ${componentName} };`;
35+
structuredCode = `const ${componentName} = (props) => (\n ${reactifiedSvg}\n);\n\nexport { ${componentName} };`;
2536
}
2637

27-
const ast: Module = await parse(structuredCode, {
28-
syntax: typescript ? "typescript" : "ecmascript",
29-
...(typescript ? { tsx: true } : { jsx: true }),
38+
const formatted = await prettier.format(structuredCode, {
39+
parser: typescript ? "typescript" : "babel",
40+
semi: true,
41+
singleQuote: false,
42+
trailingComma: "es5",
3043
});
31-
const { code } = await print(ast, { minify });
32-
return code;
44+
45+
return formatted;
3346
};

0 commit comments

Comments
 (0)