如何使用Webpack 2获取数据属性内的图像? [英] How to get image that is within a data attrbute with Webpack 2?
问题描述
我在我的图片上使用 .pug
模板和我的图片上的标准 src
属性,如下所示:
I am using .pug
templates for my HTML and standard src
attributes on my images like so:
img(src=`../images/${image}`)
当我运行 webpack -p
时, src中定义的任何图像
我的图像是由Webpack找到并放入我的 dist
目录中。这正是我期望发生的事情。
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.
但是,我现在要求延迟加载我的图像,所以我想将图像的引用放入 data-src
属性而不是标准 src
,如下所示:
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')
当我这样做时再次运行 webpack -p
,不会抓取图像。
Running webpack -p
again when I do this though, does not grab the images.
有什么方法可以让Webpack查看非src属性,意识到它需要这些图像作为生产构建的一部分?
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?
推荐答案
好的。事实证明, html-loader
有一个选项可以传递标记/属性类型,以便加载器解析,称为 attrs
,这是这些配置的数组。
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.
我实现了这样做:
{
test: /\.pug$/,
use: [
{
loader: 'html-loader',
options: {
attrs: ['img:src', 'img:data-src', 'link:href']
}
},
{
loader: 'pug-html-loader',
options: {
pretty: true,
exports: false
}
}
]
}
现在正在运行 webpack -p
似乎可以获得这些图片。
Now running webpack -p
appears to get those images.
希望这可以帮助某人出去。
Hope that this helps someone out sometime.
这篇关于如何使用Webpack 2获取数据属性内的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!