Handle Images in React using Webpack

We need to install url-loader and file-loader html-webpack-plugin npm packages first

npm install url-loader file-loader html-webpack-plugin

Now add this configuration to your webpack.config.js

const HtmlWebPackPlugin = require( 'html-webpack-plugin' );
const path = require( 'path' );
module.exports = {
	context: __dirname,
	entry: './src/index.js',
	output: {
		path: path.resolve( __dirname, 'dist' ),
		filename: 'main.js',
	},
	devServer: {
		historyApiFallback: true
	},
	module: {
		rules: [
			{
				test: /\.js$/,
				use: 'babel-loader',
			},
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader'],
			},
			{
				test: /\.(png|jp?g|svg)$/,
				use: [{
					loader: "file-loader",
					options: {
						name: '[name].[ext]',
						outputPath: 'images/',
						publicPath: 'images/'
					}
				}]
			}
		]
	},
	plugins: [
		new HtmlWebPackPlugin({
			template: path.resolve( __dirname, 'public/index.html' ),
			filename: 'index.html'
		})
	]
};

Now you can add an image inside src/images directory. Then import it as any name you like in this case ProfileIcon. And then pass it in the images source in your component.

import ProfileIcon from './images/profile-icon-min.png';

render() {
 <div>
  <img src={ProfileIcon} className="my-profile-icon" alt="profile icon"/>
 </div>
}

It will look like this in production.

So it will create an images directory in production and add the image profile-icon-min.png into it.

And the image will be dynamically added in the src attribute of img tag.

Leave a Reply