React 使用 SVG 作为组件

React SVG About 1,143 words

需求

使用Vite创建的React工程中,使用SVG作为组件直接使用,而不是通过<img>标签的src属性加载。

安装插件

vite-plugin-svgr

npm install vite-plugin-svgr --save-dev

@svgr/plugin-svgo

npm install @svgr/plugin-svgo --save-de

@svgr/plugin-jsx

npm install @svgr/plugin-jsx --save-dev

添加配置

vite.config.js中添加svgr插件。

import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'
import svgr from "vite-plugin-svgr";

// https://vite.dev/config/
export default defineConfig({
    plugins: [
        react(),
        svgr({
            include: "**/*.svg",
            svgrOptions: {
                plugins: ["@svgr/plugin-svgo", "@svgr/plugin-jsx"], // 启用 SVGO 压缩和 JSX 转换(两者需一起使用)
                svgoConfig: {
                    floatPrecision: 2, // 设置压缩精度
                },
            },
        }),],
})

使用

注意:SVG必须在src目录下。

import MyIcon from "./assets/my.svg";

export default function My() {
    return <>
        <MyIcon width={50} height={50} fill="blue"/>
    </>
}

svg.d.ts

在使用了TypeScript时,在添加widthheightfill会报错,需要添加.d.ts文件。

src下新建svg.d.ts文件,内容如下

declare module '*.svg' {
    import React from 'react';
    export default React.FC<React.SVGProps<SVGSVGElement>>
}
Views: 17 · Posted: 2025-12-13

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today In History
Browsing Refresh