React项目引入svg的方式 (CRA 和 vite)

1,976 阅读1分钟

create-react-app 项目

import { ReactComponent as SoftwareLogo } from "assets/software-logo.svg";

<SoftwareLogo width={"18rem"} color={"rgb(38, 132, 255)"} />

vite 项目

安装依赖

yarn add vite-plugin-svg-icons fast-glob -D

vite.config.ts

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

plugins: [
      ...,
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]'
      })
    ],
    

main.ts

import 'virtual:svg-icons-register';

SvgIcon

import { useMemo } from 'react'

interface SvgIconProps {
  prefix?: string
  name: string
  color?: string,
  size?: number | string
}

const SvgIcon = (props: SvgIconProps) => {
  const { prefix = 'icon', name, color, size= 16 } = props
  const symbolId = useMemo(() => `#${prefix}-${name}`, [prefix, name])
  return (
    <svg aria-hidden="true" width={size} height={size} fill={color}  >
      <use href={symbolId} fill={color} />
    </svg>
  )
}
export default SvgIcon

使用

<SvgIcon name="fengjin" color={#red} />

坑点 颜色fill 不生效

在svg源文件中 给fill 值设置为 inherit

fill="inherit"