Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load the image form the srcset attribute of the <picture> in Webpack?

I started using the tag in my Webpack app and noticed that the current setup is not working with the images referenced in the srcset:

<picture>
<source srcset="img/goal-2.jpg" media="(min-width: 675px)">
<img src="../img/goal-2-s.jpg">
</picture>

The goal-2-s.jpg is correctly resolved and copied over to my build folder, while the goal-2.jpg is ignored.

Currently my webpack.config.js config looks like this:

{
    test: /\.(jpe?g|png|gif|svg)$/i,
    loader: 'file?name=img/[name].[ext]'
},...

I don't want to auto generate files of different sizes -- I the files I'm loading are differently cropped and I do it manually and save it in my app folder. All I want is Webpack to handle my source's srcset image in the same way as it does the img's src image.

Thanks!

like image 605
Ilya Shunko Avatar asked Mar 13 '17 17:03

Ilya Shunko


People also ask

Does Srcset load all images?

Each image in srcset can be taken. So if you want to control, what is used or not used, you need to use the picture element.

What is Srcset attribute in IMG tag?

srcset defines the set of images we will allow the browser to choose between, and what size each image is. Each set of image information is separated from the previous one by a comma.

Where do you put images in Webpack?

Essentially, there is not much in Webpack to include your desired images for your web application. First, put your image files into one folder of your projects application. For instance, your src/ folder may have a folder assets/ which has a folder images/.

Do you need SRC with Srcset?

Yes it's valid. The src is used as a fallback if the browser doesn't support srcset. However if you are using it just for retina stuff you don't really need to use picturefill. I tend to just let it degrade back to the normal src if the browser doesn't support srcset.


1 Answers

The html-loader only processes the src attribute of <img> tags by default (as shown in its README). But you can use the attrs option to make it process your desired attributes by specifying an array of tag:attribute. The .html rule would look like this:

{
  test: /\.html/,
  loader: 'html-loader?attrs[]=img:src&attrs[]=source:srcset'
}

Or with the better webpack 2 options syntax:

{
  test: /\.html/,
  loader: 'html-loader',
  options: {
    attrs: ['img:src', 'source:srcset']
  }
}
like image 103
Michael Jungo Avatar answered Nov 15 '22 09:11

Michael Jungo