require function not working with image in react

◇◆丶佛笑我妖孽 提交于 2021-02-04 08:12:04

问题


I've used <img src={require('./somRelativePath/image.jpg)} in React many times. However, this time it seems not to be working. There are no errors whatsoever (such as that the image was not found etc.) but the broken image on website.

After inspecting the element I was somewhat confused by the transpiled result in browser:

<img src="[object Module]" style="width: 5rem;">

It appears as if it loads the image as a component not the acutual file. I've created the app with npx create-react-app and haven't ejected it so far. So there is no error in babel or webpack configuration as it is currently handled by react under the hood.

Importing it with import statement works just fine:

import calendarPic from '../assets/pictures/calendar.svg';

Unfortunately that's not the solution because I have the local images saved in json and it would be definitely quite repetitive and ineffective as well to load all 50 images.

With the same npx create-react-app I've made a handful of mini-projects before but have never come across such a perplexing, yet so basic error. I'd be so thankful for any response as I've skimmed every possible solution throughout the internet.

Thank you again and have a lovely day!


回答1:


I guess the problem is the location of the image. When you use create-react-app the app will be bundle into the public folder. Then the require statement would start to fetch the image - in this case in relative to the public folder and not to the src folder.

What I suggest you to do is try to move the image into the public folder and try using the src with URL relative to the public folder. Demo here



来源:https://stackoverflow.com/questions/64910839/require-function-not-working-with-image-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!