Reputation: 7324
i have a react component and i want to import an image inside of it. The image is in the same folder as the component
So i enter <img src={require('./hi.png')} />
. But the console shows an error:
Uncaught Error: Cannot find module "./hi.png"
at webpackMissingModule (bundle.js:46105)
at MainNavigationBar.render (bundle.js:46105)
at bundle.js:15841
at measureLifeCyclePerf (bundle.js:15120)
at ...
Why is that? What im doing wrong?
Upvotes: 0
Views: 5609
Reputation: 785
try to import and call your image differently :
import hi from '/assets/images/hi.png';
<div style={{ backgroud :`url(${hi})`}}>
</div>
Upvotes: 0
Reputation: 2456
I will suposse that you folder project tree is similar that and your server side was made with Nodejs, cause it was not clear in your question:
.projectFolder
|--.client
| |--.components
| |--bundle.js
| |--index.js
| |routes.js
|
|--.node modules
|--.server
|--.public
| |--.assets
| |--.images
| | |--hi.png
| |
| |--.css
|
|--index.html
|--index.js
Therefore I advise you to use a Static folder and call this using:
app.use(express.static(path.join(__dirname, 'public')));
.
So, everything inside public will be tracked and you can just callback these image with:
<img src={'/assets/images/hi.png'} width="150px" className="lateral-margin" />
Not having the necessity of use require, or anything like that. Sure, of this way your code keep more organized to other and for you too.
However, in your case require is not working because probably you neither setting your webpack nor npm installed babel-loader. Read more about loaders, download and set it with:
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
}
Upvotes: 1
Reputation: 2112
I also tried to use
<img src={require('./hi.png')} />
It is showing require is unresolved function or module
and throws the same error as not able to find hi.png
But you can use it as following way to resolve the issue
import hi from "./hi.jpg";
<img src={hi} />
Upvotes: 1