在typescript(*.tsx)文件中,我不能用下面的语句导入svg文件:
import logo from './logo.svg';
Transpiler说:[ts]找不到模块'./logo.svg'。 我的svg文件就是<svg>…</svg>。
但在.js文件中,我能够导入它没有任何问题,完全相同的导入语句。我想这与svg文件的类型有关,它必须以某种方式为ts transpiler设置。
你能在ts文件中分享一下如何做到这一点吗?
在typescript(*.tsx)文件中,我不能用下面的语句导入svg文件:
import logo from './logo.svg';
Transpiler说:[ts]找不到模块'./logo.svg'。 我的svg文件就是<svg>…</svg>。
但在.js文件中,我能够导入它没有任何问题,完全相同的导入语句。我想这与svg文件的类型有关,它必须以某种方式为ts transpiler设置。
你能在ts文件中分享一下如何做到这一点吗?
当前回答
如果你使用webpack,你可以通过创建一个自定义类型文件来做到这一点。
创建一个名为custom.d.ts的文件,内容如下:
declare module "*.svg" {
const content: React.FunctionComponent<React.SVGAttributes<SVGElement>>;
export default content;
}
将custom.d.ts添加到tsconfig。Json格式如下
"include": ["src/components", "src/custom.d.ts"]
来源:https://webpack.js.org/guides/typescript/ importing-other-assets
其他回答
如果你使用的是create-react-app 2+: docs
添加一个custom.d.ts文件(我在src目录的根路径上创建的),使用正确的类型(感谢RedMatt):
declare module '*.svg' {
const content: React.FunctionComponent<React.SVGAttributes<SVGElement>>;
export default content;
}
安装svg-react-loader或其他,然后:
使用它作为主要的svg加载器 或者如果你正在迁移一个代码库,并且不想接触工作部分(JS),请在导入时指定加载器:
import MySVG from '-!svg-react-loader!src/assets/images/name.svg'
然后将其用作JSX标记:
function f() {
return (<MySVG />);
}
如果没有其他的答案工作,尝试重新启动你的IDE(即VS Code)。对我来说,这就解决了问题。
// eslint-disable-next-line spaced-comment
/// <reference types="react-scripts" />
如果你正在使用puglin slint,可能是他已经禁用了,认为这是一个评论,但不是为了阅读SVG,你需要这个类型脚本模块,只是禁用行和高兴
我找到的解决方案:在ReactJS项目中,在文件react-app-env.d中。你可以删除评论中的空格,比如:
之前
// / <reference types="react-scripts" />
后
/// <reference types="react-scripts" />
我希望能帮到你
在CRA应用程序中导入SVG文件
如果你想在CRA应用(create-react-app)中导入SVG文件,而不做任何配置,你可以使用以下方法之一:
方法1
import { ReactComponent as MyIcon } from "./assets/images/my-icon.svg";
...
<MyIcon />
方法2
import myIconFileName from './assets/images/my-icon.svg';
...
<img src={myIconFileName} />