【问题标题】:'ReactComponent' is not exported from svg'ReactComponent' 不是从 svg 导出的
【发布时间】:2021-08-09 06:20:35
【问题描述】:

我使用 CRA 创建了一个打字稿应用程序,代码如下:

import { ReactComponent as Search } from './search.svg'

它运行良好,现在我想将此代码剥离到一个 npm 包(库)中。我首先再次运行 CRA 创建了这个包,然后删除了所有看起来不相关的内容(例如公用文件夹)。 /dist 的简化版本如下所示:

esm/
   icon/
      index.d.ts
      index.js
   index.d.ts
   index.js

这是原icon/index.ts

/// <reference types="react-scripts" />
import { ReactComponent as Search } from './search.svg'
export const Icons = {
  Search,
}

这是编译后的icon/index.d.ts

/// <reference types="react" /> <-- Changed for some reason??
export declare const Icons: {
    Search: import("react").FunctionComponent<import("react").SVGProps<SVGSVGElement> & {
        title?: string | undefined;
    }>;
};

当我尝试运行使用此库的应用时,我收到以下错误:

../dist/esm/common/icon/index.js Attempted import error:
'ReactComponent' is not exported from './search.svg' (imported as 'Search').

我该如何解决这个问题?

【问题讨论】:

  • 也停留在这个...看起来像 npmjs.com/package/@svgr/webpack 魔术,但不知道如何将它添加到 npm 包的构建/发布工具中:(
  • 解决方法可以是import Logo from '../images/logo.svg',然后是&lt;img src={Logo} alt="logo" /&gt;

标签: reactjs typescript create-react-app


【解决方案1】:

您将 svg 文件导入为默认导入,不带括号。

下面是一个例子

/// <reference types="react-scripts" />
import Search from './search.svg'
export const Icons = {
  Search,
}

【讨论】:

  • svgr 包(与 CRA 捆绑并设置)允许将导入用作 ReactComponent。这基本上设置了 svg 内联渲染,而在没有括号的情况下导入它基本上只是获取路径。
猜你喜欢
  • 2020-08-12
  • 2019-06-04
  • 2020-12-10
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多