javascriptwebpacklazy-loadingwebpack-html-loader

Webpack html-loader, include data-src image for lazy loading


I'm using webpack with html-loader to create an assets folder inside my dist folder. But I'm trying to implement lazy loading on images by changing src attribute with a data-src link.

I found in the doc that you can specify others attribute, which is what I did.

rules: [
    {
        test: /\.html$/,
        use: {
            loader: "html-loader",
            options: {
                attributes: [':srcset',':data-srcset', 'img:data-src', 'img:src', 'audio:src', 'video:src', 'track:src', 'embed:src', 'source:src', 'input:src', 'object:data', 'script:src']
            }
        }
    },
    {
        test: /\.(svg|png|jpg|jpeg|gif)$/, // Ajouter les nouveaux types quand il y en a
        use: {
            loader: "file-loader",
            options: {
                name: "[name]-[hash].[ext]",
                outputPath: "assets",
                esModule: false
            }
        }
    }
]

<img data-src="./assets/image.jpg" alt="">

When I'm running webpack, my image isn't created in the dist folder.

I found others questions here and here about that but couldn't find a good answer.


Solution

  • After 1 day of research. Turns out you need to use attrs instead of attributes. The doc seems to be wrong... So you should have something like that.

    test: /\.html$/,
    use: {
        loader: "html-loader",
        options: {
            attrs: [':srcset',':data-srcset', 'img:data-src', 'img:src', 'audio:src', 'video:src', 'track:src', 'embed:src', 'source:src', 'input:src', 'object:data', 'script:src']
        }
    }