无法在打字稿中导入 svg 文件 [英] Unable to import svg files in typescript

查看:27
本文介绍了无法在打字稿中导入 svg 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typescript(*.tsx) 文件中,我无法使用以下语句导入 svg 文件:

In typescript(*.tsx) files I cannot import svg file with this statement:

import logo from './logo.svg';

Transpiler 说:[ts] 找不到模块./logo.svg".我的 svg 文件只是 <svg>...</svg>.

Transpiler says:[ts] cannot find module './logo.svg'. My svg file is just <svg>...</svg>.

但是在 .js 文件中,我可以使用完全相同的导入语句毫无问题地导入它.我想它与 svg 文件的类型有关,必须以某种方式为 ts 转译器设置.

But in .js file I'm able to import it without any issues with exact the same import statement. I suppose it has something to do with type of svg file which must be set somehow for ts transpiler.

您能分享一下如何在 ts 文件中进行这项工作吗?

Could you please share how to make this work in ts files?

推荐答案

如果你使用 webpack,你可以通过创建自定义类型文件来实现.

If you use webpack, you can do this by creating a custom types file.

创建一个名为 custom.d.ts 的文件,内容如下:

Create a file named custom.d.ts with the following content:

declare module "*.svg" {
  const content: any;
  export default content;
}

custom.d.ts 添加到 tsconfig.json 如下

"include": ["src/components", "src/custom.d.ts"]

来源:https://webpack.js.org/guides/typescript/#importing-other-assets

这篇关于无法在打字稿中导入 svg 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆