简体   繁体   English

如何在react中导入webp图片 typescript

[英]How to import webp image in react typescript

I have searched the answer, but couldn't find any我已经搜索了答案,但找不到任何
When importing an image in *.webp in typescript there is a need for declaration file, eg declaration.d.ts在 typescript 中导入 *.webp 中的图像时需要声明文件,例如declaration.d.ts

In there must be provided something similar to follow up code:必须提供类似于后续代码的内容:

declare module "*.webp" {
    const value: any;
    export = value;
}

After it, the import method is之后,导入方法是

import * as img from "path/to/image/img.webp"

<img src={img} alt="404" />

However, after the render no image will show up, because what is essentially exported is not an image itself but an [object Module].然而,在渲染之后不会显示任何图像,因为本质上导出的不是图像本身,而是一个[对象模块]。 Which can be easily seen with this这可以很容易地看出

console.log(img)

In that img module is the path to put in, so the following can be used:在那个img模块中是要放入的路径,所以可以使用如下:

<img src={img.default} alt="404"/>

But I'm pretty certain, A) I am declaring in a very wrong way, ie there must be a better export in declaration or better type to be written against value B) I am using import in a wrong way.但我很确定,A) 我以一种非常错误的方式声明,即必须有更好的声明导出或更好的类型来写入B) 我以错误的方式使用导入。

So I am open for the better ways to deal with WebP import in React TS.所以我对在 React TS 中处理 WebP 导入的更好方法持开放态度。 Help from you or links to rtfm will be much appreciated.非常感谢您的帮助或指向 rtfm 的链接。 Thank you!谢谢!

TypeScript gives an error if you try to import webp image as ReactComponent .如果您尝试将webp图像作为ReactComponent导入,TypeScript 会报错。 So you should not import it as a component, but use only the source of image.因此,您不应将其作为组件导入,而应仅使用图像 Check this example:检查这个例子:

import img from "./images/image.webp";

Now you can use this src in any of your tag like this.现在你可以像这样在你的任何标签中使用这个 src。

<img src={img} />

In fact you have to use事实上你必须使用

import img from "./images/image.webp";

and then然后

<img src={img.src} />

this way it works这样就可以了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM