I'm creating an app using **reactjs **and **typescript **however I encountered an issue while loading **images **inside a component.
My error in console
Uncaught Error: Cannot find module '../images/test.png'
at webpackEmptyContext...
This is my component:
import { IProject } from '../interfaces/IProject'
import pin from '../svgs/pin.svg'
function Project(props: { project: IProject }) {
const project = props.project
return (
<>
<div className='project'>
<img className='pin' src={pin} alt='pin' />
<div>
<img alt='project gif' src={require(project.image)} />
<span>{project.title}</span>
</div>
</div>
</>
)
}
export default Project
NB : The images are stored inside a 'images' folder and the project component is stored inside a 'components' folder **NB#2 : **the first image 'pin' loads normally.
Thank you for all the help ~ sorry if this a nooby question.
I tried
- replacing
(project.image)
with('../images/test.png')
and it works if I do that but I want to be able to display the image src passed by the props. - for testing purposes, I added a
const projectImage = '../images/test.png
and replacingrequire(project.image)
withrequire(projectImage)
and it doesn't work - I created index.d.ts file (according to solutions I found on the internet) and added
declare module '*.jpg'
and the same thing for jpeg and png. It didn't fix my issue - changing the path of the image
- I also installed file-loader
CodePudding user response:
update variable value to contain only the name like this
project.image = 'test.png'
then add the relative path
require(`../images/${project.image}`)