【问题标题】:Adding svgr to create-react-app via craco通过 craco 将 svgr 添加到 create-react-app
【发布时间】:2020-05-21 06:25:33
【问题描述】:

我想使用 svgr's webpack plugin 和 create-react-app 到 use SVGs with MaterialUI's 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.

我的 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;
    }
  }
};

如何正确嵌入 SVG?

【问题讨论】:

  • 如果你想添加一个加载器,使用unshift()而不是push()给你的加载器高优先级

标签: webpack create-react-app craco


【解决方案1】:

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

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

GoogleLogo 现在是一个组件。

ReactComponent 是必需的魔术字符串。

【讨论】:

  • 这太棒了 - 出于好奇,你有这方面的任何文档链接吗?
  • 看起来 CRA 在没有 CRACO 的情况下已经支持此功能。
  • 这个提示太棒了!但不适用于我的 antd 设置.... import {Icon} from 'antd';从'../../images/tree.svg'导入{ReactComponent as Tree};
猜你喜欢
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2018-07-01
  • 2021-08-05
  • 2019-02-16
相关资源
最近更新 更多