Reputation: 15293
here is my webpack.config:
const HtmlPlugin = require("html-webpack-plugin");
const path = require("path");
module.exports = {
watch: true,
output:{
path:path.resolve(__dirname, "build"),
filename:"bundle.js"
},
module:{
rules:[
{
test:/\.(js|jsx)$/,
exclude:/node_modules/,
use:[{loader:"babel-loader"}]
},
{
test:/\.html$/,
use:[{loader:"html-loader"}]
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [{loader: 'file-loader'}],
}
]
},
plugins:[
new HtmlPlugin({
filename:"index.html",
template:"./src/index.html"
})
],
devtool: 'inline-source-map',
devServer:{
historyApiFallback:true,
port:5000
}
}
i am importing image in index.js:
import React from "react";
import ReactDOM from "react-dom";
import Img from "./images/flower.jpg";
const App = () => {
return (
<div>
<h1>Hello World!!</h1>
<img src="{Img}" />
</div>
)
};
ReactDOM.render(<App />, document.getElementById("root"));
But when i start the app, no images loaded. it looks like:
and getting some warring message like :
"webpack performance recommendations: You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application. For more info visit https://webpack.js.org/guides/code-splitting/"
how to solve this? I use "webpack": "^5.11.0", "webpack-cli": "^4.2.0",
Thanks in advance.
Upvotes: 1
Views: 2953
Reputation: 409
The Webpack 5 docs state that you can use the built in asset modules, so you don't need file-loader
: https://webpack.js.org/guides/asset-management/#loading-images
In your webpack config file, change your image handling rule to:
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
In index.js
, change <img src="{Img}" />
to <img src={Img} />
(as Magofoco suggested).
Upvotes: 5
Reputation: 5446
I am not sure if you copied you code wrong, but it is not correct. You put "{Img}"
between quotes, but it should be without: {Img}
Wrong:
import Img from "./images/flower.jpg";
const App = () => {
return (
<div>
<h1>Hello World!!</h1>
<img src="{Img}" /> <-- HERE IT IS NOT A VARIABLE
</div>
)
};
Correct:
import Img from "./images/flower.jpg";
const App = () => {
return (
<div>
<h1>Hello World!!</h1>
<img src={Img} /> <-- WITHOUT "" IT IS A VARIABLE
</div>
)
};
See: https://codesandbox.io/s/infallible-poincare-5yvcn
Upvotes: 1