关于react.js:react项目中使用svgspriteloader按需加载svg

3次阅读

共计 1106 个字符,预计需要花费 3 分钟才能阅读完成。

svg 组件

import React, {useRef, useMemo, useState, useEffect} from 'react'

import '@/styles/components/svg/index.scoped.scss'

type IImport = {
  default?: Record<string, any>
  [key: string]: any
}

type ISvg = {
  iconClass: string
  className?: string
  width?: number
  height?: number
  color?: string
  style?: Record<string, any>
  onClick?: () => void}

const SvgIcon: React.FC<ISvg> = (props: any) => {
  const {
    iconClass,
    className,
    width = 16,
    height = 16,
    color = '#000',
    style = {},
    onClick,
  } = props
  const [svgModule, setSvgModule] = useState<IImport>()

  const getSvg = async () => {const svg = await import(`../../icons/svg/${props.iconClass}.svg`)
    setSvgModule(svg)
  }

  const iconPath = useMemo(() => {if (svgModule && svgModule.default) {return `#${svgModule.default.id}`
    }
  }, [iconClass, svgModule])

  const Style = {
    ...style,
    width: `${width}px`,
    height: `${height}px`,
    color,
  }

  useEffect(() => {getSvg()
  }, [])

  return (
    <svg
      onClick={onClick}
      style={Style}
      className={`svg-icon ${className}`}
      aria-hidden="true"
    >
      <use xlinkHref={iconPath} />
    </svg>
  )
}

export default SvgIcon

webpack 配置 –loader

{test: /\.(svg)$/,
  loader: 'svg-sprite-loader',
  exclude: [/node_modules/],
  include: [resolve('../app/icons/svg')],
  options: {
    // extract: true,
    symbolId: 'icon-[name]',
  },
},
正文完
 0