使用 Vite 将 SVG 文件导入为 React 组件

2025-06-08

使用 Vite 将 SVG 文件导入为 React 组件

如果您曾经使用过create-react-app并且想要将 SVG 文件导入为 React 组件,那么您可能会做这样的事情,而且它就成功了™:

import { ReactComponent as Logo } from './logo.svg'
Enter fullscreen mode Exit fullscreen mode

但是,唉,如果你像我一样开始更频繁地使用 Vite,你就不能这样做了。

别害怕,一切仍有可能!

进入vite-plugin-svgr

vite-plugin-svgr是一款 Vite 插件,可以将 SVG 转换为 React 组件!使用起来非常直观:

npm install vite-plugin-svgr
Enter fullscreen mode Exit fullscreen mode

将其添加到您的vite.config.js

import svgr from 'vite-plugin-svgr'

export default {
  // ...
  plugins: [svgr()],
  // ...
}
Enter fullscreen mode Exit fullscreen mode

然后,你就得到了预期的行为!

// somewhere in your React + Vite app

import { ReactComponent as WhateverIcon } from "./icons/WhateverIcon.svg";

// ...

export default function SomeComponent() {
    return (
        <div>
            <WhateverIcon />
            Wow, I love icons, because I am a dweeb
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

如果您使用像MUI这样的库并且需要使用自定义图标,这将特别有用,如下所示:

// somewhere in your React + Vite app

import { Box, IconButton, SvgIcon } from "@mui/material";
import { ReactComponent as WhateverIcon } from "./icons/WhateverIcon.svg";

// ...

export default function SomeComponent() {
    return (
        <Box>
            <IconButton aria-label="some icon">
                <SvgIcon>
                    <WhateverIcon />
                </SvgIcon>
            </IconButton>
            Wow, I love icons, because I am a dweeb
        </Box>
    );
}
Enter fullscreen mode Exit fullscreen mode

您还可以用 做其他事情vite-plugin-svgr,这里有一个选项列表

希望这对您有帮助,祝您图标使用愉快!

鏂囩珷鏉ユ簮锛�https://dev.to/cassidoo/importing-svg-files-as-react-components-with-vite-l3n
PREV
驼鹿事实 mooselife
NEXT
共同创作 Git 提交