Search code examples
htmlwebpackwebpack-3

how to use webpack for html5 srcset images


In development mode i am using require for html images and compiling using webpack.

Html:

Below code is compiled using webpack and return output as normal html but how to use it for html5 srcset 2x 3x images?

<img src=<%=require("./images/test.png") %><!-compiled properly-->

<img src=<%=require("./images/test.png") %> srcset="images/test-2x.png 2x, images/test-3x.png 3x" class="img-fluid" />

Solution

  • In webpack.config.js Install srcset loader after that use the rules below.

     module: {
                rules: [
                       {
                        test: /\.(gif|png|jpg|svg)$/i,
                        use:[
                            {
                                loader: 'srcset-loader',
                            },
                            'file-loader?name=[name].[ext]&outputPath=images/',
                            'image-webpack-loader']
                      }
    }
    

    Html:

     <img src=<%=require("./images/test.png")%> srcset="<%=require("./images/test-2x.png")%> 2x ,<%=require("./images/test-3x.png")%> 3x" class="img-fluid" />
    

    Now using this code webpack will optimize 2x 3x images in production mode.