【问题标题】:SVG with React via svgr failing通过 svgr 使用 React 的 SVG 失败
【发布时间】:2020-01-10 14:58:03
【问题描述】:

在 webpack 配置中有这个:

  module: {
    rules: [
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      }
    ]
  },

还有一个简单的导入组件

import Globe from './Globe.svg'

(...)
<div>
  <Globe />
</div>

导致以下错误,整个页面呈现硬停止。

Warning: <data:image/svg+xml;base64,ZnVuY3Rpb24gX2V... (more here)0.=87…
...BkZWZhdWx0IFN2Z0NvbXBvbmVudDs= /> is using incorrect casing. 
Use PascalCase for React components, or lowercase for HTML elements.

【问题讨论】:

  • 你找到解决方案了吗?

标签: reactjs svg


【解决方案1】:

这似乎是已知问题https://github.com/smooth-code/svgr/issues/83

我建议包括url-loaderhttps://www.smooth-code.com/open-source/svgr/docs/webpack/#using-with-url-loader-or-file-loader

在你的 webpack.config.js 中:

{   test: /\.svg$/,   use: ['@svgr/webpack', 'url-loader'], }

在您的代码中:

import starUrl, { ReactComponent as Star } from './star.svg' 
const App = () => (
  <div>
    <img src={starUrl} alt="star" />
    <Star />
  </div>
)

【讨论】:

  • 谢谢!我也偶然发现了这个。当我尝试使用 { ReactComponent as Star } 时,我得到的只是“未定义”并伴有错误:您可能忘记从定义它的文件中导出组件,或者您可能混淆了默认导入和命名导入。跨度>
  • 你能把你的文件svg放到codesanbox吗?所以我们可以重现它。
  • { ReactComponent as Something } 不是特定于 create-react-app 的吗?我在 Next.js 项目中遇到了同样的错误。
  • 不,这就是create-react-app 配置webpack的方式
猜你喜欢
  • 2021-07-23
  • 2019-11-06
  • 2021-10-29
  • 2022-08-12
  • 2022-01-07
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
相关资源
最近更新 更多