Search code examples
webpackcreate-react-appcraco

Adding svgr to create-react-app via craco


I want to use svgr's webpack plugin with create-react-app to use SVGs with MaterialUI's SvgIcon. I'm using craco to add svgr to Webpack's config.

Currently, whenever the SVG is supposed to be rendered, the following error is thrown:

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

My craco.config.js:

const CracoAlias = require("craco-alias");

module.exports = {
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        baseUrl: "./src",
        tsConfigPath: "./tsconfig.extend.json",
        source: "tsconfig"
      }
    }
  ],
  webpack: {
    configure: (config, { env, paths }) => {
      config.module.rules.push({
        test: /\.svg$/,
        use: ["@svgr/webpack"]
      });
      return config;
    }
  }
};

How do I embed the SVG properly?


Solution

  • It looks like CRA supports converting SVGs by default, thus making craco+svgr redundant.

    import { ReactComponent as GoogleLogo } from "../assets/images/googlelogo.svg";
    

    GoogleLogo is a component now.

    ReactComponent is a required magic string.