React + Vite 项目中如何使用 SVG

1,786 阅读1分钟

如果你使用的构建工具是 Vite, 那么这篇文章对你或许有些帮助。


Vite 插件地址: Vite plugin to transform SVGs into React components

安装插件:

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

修改 vite.config.ts 配置:

import svgr from "vite-plugin-svgr"; // 新增

export default defineConfig({
  plugins: [
      react(), 
      svgr() // 新增
  ],
  // ...
});

tsconfig.json 中添加类型:

{
  "compilerOptions":{
      // ...
      "types": ["vite-plugin-svgr/client", "node"],
  }
}

使用一:携带后缀 ?react

import AdminSvg from "@/assets/svg/admin.svg?react"; // !不要遗漏 ?react

const Login = () => {
  return (
    <div>
      <AdminSvg />
    </div>
  );
};

export default Login;

使用二:如果你不想要每次编写后缀,你需要修改 vite.config.ts 配置,确保在使用 svgr 插件时指定了 include 字段。如下:

svgr({ include: "src/assets/svg/*.svg" })

参考 Issue: Issue #107 · pd4d10/vite-plugin-svgr

这种方法的缺陷是当你为 svg 组件赋予类名时会出现 ts 类型报错。


如果在使用过程中遇见下面报错:

Failed to execute 'createElement' on 'Document': The tag name provided ('/src/assets/svg/xxx.svg') is not a valid name.

很有可能是你遗漏了 ?react 后缀。