通过 craco 将 svgr 添加到 create-react-app

Joh*_*ith 4 webpack create-react-app craco

我想将svgr 的 webpack 插件与 create-react-app 一起使用,以将 SVG 与 MaterialUI 的 SvgIcon一起使用。我正在使用craco将 svgr 添加到 Webpack 的配置中。

目前,每当应该渲染 SVG 时,都会抛出以下错误:

Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/googlelogo.03ad8507.svg') is not a valid name.
Run Code Online (Sandbox Code Playgroud)

我的 craco.config.js:

Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/googlelogo.03ad8507.svg') is not a valid name.
Run Code Online (Sandbox Code Playgroud)

如何正确嵌入 SVG?

Joh*_*ith 14

看起来 CRA 默认支持转换 SVG,从而使 craco+svgr 变得多余。

import { ReactComponent as GoogleLogo } from "../assets/images/googlelogo.svg";
Run Code Online (Sandbox Code Playgroud)

GoogleLogo 现在是一个组件。

ReactComponent 是必需的魔法字符串。

  • @prestonsmith https://create-react-app.dev/docs/adding-images-fonts-and-files/#adding-svgs (2认同)