React recently made a UI library to implement SVG in the project

Start with a few SVG files for testing, in the following directory

Lib/Below is the source code directly, and the ICONS folder contains the SVG file

//index.tsx acts like main.js and react renders nodes
import React from 'react';
import ReactDOM from 'react-dom'
import Icon from './icon'

ReactDOM.render(
  <div>
    <Icon name="wechat"/>
  </div>
,document.querySelector('#root'))
Copy the code

The icon. TSX function component returns a span containing an SVG image. The react dynamic import of SVG can be set as follows

import React from 'react';
import './icons/alipay.svg'
import './icons/wechat.svg'
import './icons/byte.svg'

interfaceIconProps { name? :string;
}
const Icon:React.FunctionComponent<IconProps>=(props) = >{
  return (
    <span>
      <svg className="icon" >
          <use xlinkHref={` # ${props.name} `} / >
      </svg>
      <svg className="icon" >
          <use xlinkHref='#alipay'/>
      </svg>
      <svg className="icon" >
          <use xlinkHref='#byte'/>
      </svg>
      icon
    </span>
  );
}

export default Icon;
Copy the code

Installation of svG-sprite-loader Used to import SVG files

yarn add svg-sprite-loader
Copy the code

Module.exports {module{rules[]}} specifies that SVG files use svG-sprite-loader

{
  test:/.svg$/,
  loader: 'svg-sprite-loader'
}
Copy the code

Using syBOL import, when running server, you can see that the console HTML Element introduces SVG into syBOL tags.

<svg class="icon" aria-hidden="true"> 
    <use xlink:href="#icon-xxx"></use> 
</svg>
Copy the code

However, an error is reported if you use import XXX from

Console errorERROR in [at-loader] ./lib/icon.tsx:2:21 TS2307: Cannot find module './icons/alipay.svg' or its corresponding type declarations. Module not foundBecause it’s always been a direct import way to load, andimport xxx fromIt needs to be exported as a module, but SVG without export default will report an error if exported. To use this method, you need to configure the D.js file.

I looked at this error handling method on the web and I named it custom.d.s. Put it in the types directory and write the following code

declare module '*.svg' {
  const content: any;
  export default content;
}
Copy the code

The error disappeared, and the console did not report an error