Adding svgr to create-react-app via craco
Asked Answered
D

1

6

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?

Daradarach answered 5/2, 2020 at 10:48 Comment(1)
if you want to add a loader, use unshift() instead of push() to give your loader high priorityFakieh
D
28

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.

Daradarach answered 5/2, 2020 at 11:2 Comment(4)
This is awesome - you have any documentation links on this at all, just out of curiosity?Merchant
@Merchant create-react-app.dev/docs/adding-images-fonts-and-files/…Daradarach
It looks like CRA already supports this feature without CRACO.Schlesien
This hint is amazing! Does not work with my antd setup though.... import {Icon} from 'antd'; import {ReactComponent as Tree} from '../../images/tree.svg'; <Icon component={Tree} />Ole

© 2022 - 2024 — McMap. All rights reserved.