react18 ts中使用 svg

2022-12-14  本文已影响0人  VIAE

create-react-app中已经集成@svgr/webpack
webpack.config.js

module:[
    rules:[
        {
            test:/\.svg$/,
            use:[
                {
                  loader:require.resolve("@svgr/webpack"),
                  options:{
                    prettire:false,
                    svgo:false,
                    svgoConfig:{
                      plugins:[{removeViewBox:false}],
                    },
                    titleProp:true,
                    ref:true
                  }
                }
            ],
            issuer:{
              and:[/.(ts|tsx|js|jsx|md|mdx)/]
            },
            resourceQuery:{not:[/url/]}
        },
        {
          test:/\.svg$/,
          type:'asset',
          issuer:{
            and:[/.(ts|tsx|js|jsx|md|mdx)/]
          },
          resourceQuery:/url/
        }
    ]
]

react-app-env.d.ts

...
declare module '*.svg'{
  import * as React from 'react';
  
  export const ReactComponent:React.FunctionComponent<React.SVGProps<SVGSVGElement> & {title?:string}>;
  
  const content:ReactComponent;
  export default content;
}

declare module '*.svg?url'{
  const src:string;
  export default src;
}
...

使用方法
方法一:矢量图引入

import Add from '@Icons/tianjia.svg'

<Add width="30px" height={30}/>

方法二:作为图片被引入 必须携带 ?url,与svgComponent区分开

import Change from '@Icons/qiehuan.svg?url'

<img src={Change}/>
上一篇 下一篇

猜你喜欢

热点阅读