react项目中使用svg-sprite-loader按需加载svg

Posted 万年打野易大师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react项目中使用svg-sprite-loader按需加载svg相关的知识,希望对你有一定的参考价值。

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]\',
  },
},

以上是关于react项目中使用svg-sprite-loader按需加载svg的主要内容,如果未能解决你的问题,请参考以下文章

react---react项目中如何使用iconfont

create-react-app创建react项目,使用axios跨域

如何使用React删除待办事项列表中的项目

通过索引选择数组中的项目,同时使用 React 钩子

在react typescript项目中如何使用没有@type定义的npm包

如何将 React 组件导出为 NPM 包以在单独的项目中使用?