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.
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']
}
}
The correct syntax for now (webpack 4) is as follows:
{
test: /\.html$/i,
use: {
loader: 'html-loader',
options: {
sources: {
list: [
"...", // important, to correctly handle the default tags like 'src'
{
tag: "img",
attribute: "data-src",
type: "src",
},
]
}
}
}
}
You'll find a detailed description here: https://webpack.js.org/loaders/html-loader/#sources
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With