@@ -2,14 +2,14 @@ import { readFileSync } from "fs";
2
2
import { transform } from "esbuild" ;
3
3
import { Plugin } from "vite" ;
4
4
5
- export function svgPlugin ( ) : Plugin {
5
+ export function svgPlugin ( opts ?: { useInnerHTML ?: boolean } ) : Plugin {
6
6
return {
7
7
name : "svg" ,
8
8
enforce : "pre" ,
9
9
async load ( id ) {
10
10
if ( id . endsWith ( ".svg" ) ) {
11
11
const { code, warnings } = await transform (
12
- svgToJSX ( readFileSync ( id , "utf-8" ) ) ,
12
+ svgToJSX ( readFileSync ( id , "utf-8" ) , opts ?. useInnerHTML ) ,
13
13
{ loader : "jsx" }
14
14
) ;
15
15
for ( const warning of warnings ) {
@@ -27,15 +27,30 @@ export function svgPlugin(): Plugin {
27
27
} ;
28
28
}
29
29
30
- export const svgToJSX = ( svg : string ) =>
31
- `import React from "react";const ReactComponent = (props) => (${ svg
32
- . replace ( / \s ( [ a - z - :] * ) = " [ ^ " ] * " / gu, ( string , key : string ) => {
33
- if ( key . startsWith ( "data-" ) ) return string ;
34
- const keyWithoutDashes = camelCaseOn ( key , "-" ) ;
35
- const keyWithoutDots = camelCaseOn ( keyWithoutDashes , ":" ) ;
36
- return string . replace ( key , keyWithoutDots ) ;
37
- } )
38
- . replace ( ">" , " {...props}>" ) } );export default ReactComponent`;
30
+ export const svgToJSX = ( svg : string , useInnerHTML ?: boolean ) => {
31
+ let jsx : string ;
32
+ if ( useInnerHTML ) {
33
+ const index = svg . indexOf ( ">" ) ;
34
+ const content = svg
35
+ . slice ( index + 1 , svg . indexOf ( "</svg>" ) )
36
+ . trim ( )
37
+ . replace ( / \s + / g, " " ) ;
38
+ jsx = `${ updatePropsCase (
39
+ svg . slice ( 0 , index )
40
+ ) } {...props} dangerouslySetInnerHTML={{ __html: '${ content } ' }} />`;
41
+ } else {
42
+ jsx = updatePropsCase ( svg ) . replace ( ">" , " {...props}>" ) ;
43
+ }
44
+ return `import React from "react";const ReactComponent = (props) => (${ jsx } );export default ReactComponent;` ;
45
+ } ;
46
+
47
+ const updatePropsCase = ( svg : string ) =>
48
+ svg . replace ( / \s ( [ a - z - :] * ) = " [ ^ " ] * " / gu, ( string , key : string ) => {
49
+ if ( key . startsWith ( "data-" ) ) return string ;
50
+ const keyWithoutDashes = camelCaseOn ( key , "-" ) ;
51
+ const keyWithoutDots = camelCaseOn ( keyWithoutDashes , ":" ) ;
52
+ return string . replace ( key , keyWithoutDots ) ;
53
+ } ) ;
39
54
40
55
const camelCaseOn = ( string : string , delimiter : string ) =>
41
56
string
0 commit comments