Search code examples
javascriptwebpackpugwebpack-dev-serverwebpack-2

How to get image that is within a data attrbute with Webpack 2?


I am using .pug templates for my HTML and standard src attributes on my images like so:

img(src=`../images/${image}`)

When I run webpack -p, any images defined in the src's of my images are found by Webpack and placed into my dist directory. This is exactly what I would expect to happen.

However, I now have a requirement to lazy load my images, so I want to place the reference to the image into a data-src attribute instead of the standard src, like so:

img(data-src=`../images/${image}` src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')

Running webpack -p again when I do this though, does not grab the images.

Is there any way that I can make Webpack look at non-src attributes to realise that it requires those images as part of the production build?


Solution

  • Okay. It turns out that html-loader has an option to pass in tag / attribute types for the loader to parse through, called attrs, which is an array of these configurations.

    I achieved this doing it like so:

    {
      test: /\.pug$/,
      use: [
        {
          loader: 'html-loader',
          options: {
            attrs: ['img:src', 'img:data-src', 'link:href']
          }
        },
        {
          loader: 'pug-html-loader',
          options: {
            pretty: true,
            exports: false
          }
        }
      ]
    }
    

    Now running webpack -p appears to get those images.

    Hope that this helps someone out sometime.