Serving Static Images In React Application Using Webpack
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!