为什么我必须使用“require"?而不是“进口自"React 中的图像? [英] Why do I have to use "require" instead of "import from" for an image in React?

查看:37
本文介绍了为什么我必须使用“require"?而不是“进口自"React 中的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到 this answer 建议了用于导入图像的语法,如下所示(已注释掉).就我而言,它没有解决(抱怨在该文件中找不到模块),我不得不切换到当前处于活动状态的语法.

I see that this answer suggests the syntax for importing images as shown below (commented out). In my case, it didn't work out (complaining there's no modules to find in that file) and I had to switch to the syntax that's currently active.

// import Author from "../assets/author.png";
var Author = require("../assets/author.png");

我可以想象的不同之处在于我使用的是 TypeScript(通过 awesome-typescript-loader 转换我的 TSX 并加载我的 PNG file-loader),它们似乎使用 JSX.但就我的理解而言,它最终都会转换为纯 JS 和 require.

The difference I can imagine is that I'm using TypeScript (transpiling my TSX by awesome-typescript-loader and loading my PNG file-loader) and they seem to use JSX. But as far my understanding goes, it all transpiles to plain JS and require in the end.

作为 React 的菜鸟,我不确定这种差异的原因是什么但也我不确定要通过谷歌搜索什么来调查自己.

Being a noob on React, I'm not sure what the reason of this discrepancy is but also I'm not sure what to google for to investigate myself.

推荐答案

你可以像这样为你的图片声明一个模块:

You can declare a module for your images like this:

declare module "*.png" {
  const value: any;
  export default value;
}

然后,您将能够像这样导入图像:

Then, you will be able to import your image like this:

import AuthorSrc from "../assets/author.png";

发生这种情况是因为 webpack 不支持开箱即用的图像导入.因此,您需要在 webpack 配置文件中为此添加规则.当您添加新规则时,TypeScript 不会自动知道这一点,因此您需要声明一个新模块来解决此问题.如果没有该模块,您将能够导入图像,但 TypeScript 会抛出错误,因为您没有告诉它是可能的.

This is happening because webpack doesn't support image import out of the box. So you need to add a rule for that in the webpack config file. When you add a new rule, TypeScript doesn't automatically know that, so you need to declare a new module to resolve this. Without the module, you will be able to import images, but TypeScript will throw an error because you didn't tell to it is possible.

这篇关于为什么我必须使用“require"?而不是“进口自"React 中的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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