我使用 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').
我该如何解决这个问题?
我原来的答案不太清楚,并且没有考虑到您正在使用 create-react-app 的事实。
由于您使用的是 create-react-app,SVGR 库已安装并用于作为 ReactComponent 处理 SVG 文件。
您可以像这样直接导入它们:
import Search from './search.svg'
然后像这样使用它:
export const Component = () => {
return (
<div>
<Search />
</div>
);
}
为什么它之前可以工作,然后在将代码移动到另一个 npm 包后停止工作的原因可以在react-scripts webpack 配置中找到(由 CRA 使用)。
我在使用 [email protected] 时遇到了同样的问题,问题是如何应用 svg loader。请注意,该规则仅适用于目标应用程序的 src 文件夹。因此,这只适用于代码位于目标包中的情况,一旦它移动到自己的 npm 包,在编译应用程序时,react-scripts webpack 配置将不再处理 svg 导入。
解决方案是使用这些 svg 导入作为字符串路径(通过 svg 文件的默认导出),然后将它们用作您的 src 反应组件。
import searchIconPath from './search.svg';
export const SearchIcon = () => <img src={searchIconPath} />;
此方法有效的原因是
file-loader
应用于所有文件。
我相信(查看代码,我还没有尝试过)这个问题现在已在最新版本的react-scripts中修复,因为该规则现在在全球范围内应用得更多。
您将 svg 文件作为默认导入导入,不带括号。
下面是一个例子
/// <reference types="react-scripts" />
import Search from './search.svg'
export const Icons = {
Search,
}