Serving Static Images In React Application Using Webpack

Imran Sayed
2 min readMay 29, 2021

In this blog we will learn about how to serve static images.

Add your images to a relative path in your source. Let’s say your entry point is src . Then create an images folder, and place your images inside of it.

Then `npm install file-loader` add the below config with `use: ‘file-loader?name=./images/[name].[ext]’`.

module.exports = {
context: __dirname,
entry: './src/index.js',
output: {
path: path.resolve( __dirname, 'dist' ),
filename: 'main.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.(png|j?g|svg|gif)?$/,
use: 'file-loader?name=./images/[name].[ext]'
}
]
},
}

This will output the following on build

Now there are two ways to use image in React App.

import NetflixBackgroundImg from '../../images/netflix-background.png';
<img src={NetflixBackgroundImg} alt="my-logo"/>

or

import '../../images/netflix-background.png';
<img src="/images/netflix-background.png" alt="my-logo"/>

Notice that you still need to import the image, else webpack won’t output the image in the dist folder.

Source code on Github

That’s all folks!

--

--

Imran Sayed

👤 Full Stack Developer at rtCamp, Speaker, Blogger, YouTuber, Wordpress, React, Node, Laravel Developer http://youtube.com/ImranSayedDev