语境
为了使一些代码部分在许多 react 项目中可重用,我有以下项目结构:
@foo/design
: 包含设计内容,例如原始 svg 图片 @foo/ui
: 基于 Create React App for common 组件的 react 库 @foo/project
: 使用 foo/ui
的最终 CRA 项目图书馆
foo/ui
库导出一些从 @foo/design
导入 svg 图像的组件:// MyComponent.ts
import React, { FC } from 'react';
import {
ReactComponent as Logo,
} from '@foo/design/static/img/logo.svg';
export const MyComponent: FC = () => {
return (
<div>
Some stuff.
<Logo />
</div>
);
};
export default null;
此组件在 @foo/ui
的相关 Storybook 实例上完美运行并使用 tsc
编译像这样:// MyComponent.js
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { ReactComponent as Logo, } from '@foo/design/static/img/logo.svg';
export var Navbar = function () {
return (_jsxs("div", { children: ["Some stuff.", _jsx(Logo, {}, void 0)] }, void 0));
};
export default null;
这里也是相关的tsconfig.json
文件:{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"declaration": true,
"outDir": "./lib",
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx"
},
"include": ["src"],
"exclude": [
"src/samples",
"src/**/*.stories.*",
"src/**/*.test.*",
"src/setupTests.js"
],
}
项目导入在
@foo/project
,我添加了@foo/ui
依赖,安装@foo/design
包也一样(@foo/ui
需要)。我以这种方式使用我的组件:
import { FC } from 'react';
import { MyComponent } from '@foo/ui'
const App: FC = () => {
return (
<MyComponent />
);
}
export default App;
但这会产生以下错误:Failed to compile.
./node_modules/@foo/ui/lib/MyComponent.js
Attempted import error: 'ReactComponent' is not exported from '@foo/design/static/img/logo.svg' (imported as 'Logo').
但是,如果我从 MyComponent.js
复制/过去 svg 导入行直接在我的根应用程序组件上:import { FC } from 'react';
import { ReactComponent as Logo, } from '@foo/design/static/img/logo.svg';
const App: FC = () => {
return (
<Logo />
);
}
export default App;
这有效,svg 按预期显示。这里也是CRA项目相关
tsconfig.json
文件:{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
为什么 ReactComponent
从我的导入库完成后,CRA 导入不起作用?解决此问题的最简单方法是@foo/ui
只在内部使用?谢谢
最佳答案
我发现在类似情况下唯一的解决方法可以帮助我-
内联定义 SVG 组件,使用 https://svg2jsx.com/准备组件。
因此,在您的情况下,您将无法使用 @foo/design
中的共享 SVG。创建一个包装器组件,但至少您可以在 @foo/ui
中准备共享的 SVG 组件.
花了很多时间,最近才解决它,所以无法解释根本问题是什么。
关于javascript - 如何使用 create-react-app 从外部模块导入 svg react 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67320996/