|
1 | | -import { parse, print, type Module } from "@swc/core"; |
| 1 | +import prettier from "prettier"; |
2 | 2 |
|
3 | 3 | interface ParseReactSvgOptions { |
4 | 4 | componentName: string; |
5 | 5 | svgCode: string; |
6 | 6 | typescript: boolean; |
7 | | - minify?: boolean; |
8 | 7 | } |
9 | 8 |
|
10 | 9 | export const parseReactSvgContent = async ({ |
11 | 10 | componentName, |
12 | 11 | svgCode, |
13 | 12 | typescript, |
14 | | - minify = false, |
15 | 13 | }: 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="'); |
17 | 27 |
|
| 28 | + let structuredCode = ""; |
18 | 29 | if (typescript) { |
19 | 30 | structuredCode = |
20 | 31 | `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` + |
22 | 33 | `export { ${componentName} };`; |
23 | 34 | } 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} };`; |
25 | 36 | } |
26 | 37 |
|
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", |
30 | 43 | }); |
31 | | - const { code } = await print(ast, { minify }); |
32 | | - return code; |
| 44 | + |
| 45 | + return formatted; |
33 | 46 | }; |
0 commit comments