dazuaz / responsive-loader

A webpack loader for responsive images
BSD 3-Clause "New" or "Revised" License
647 stars 74 forks source link

[DOCS] How to use responsive-loader with Pug #156

Closed webdiscus closed 2 years ago

webdiscus commented 2 years ago

Hello @dazuaz,

Thank you for your great responsive-loader!

I'm author of the pug-plugin for Webpack and I have added supports for the responsive-loader in Pug.

Description of the problem

In Pug the access to the object properties, e.g. require('image.jpg?sizes[]=100,sizes[]=200,sizes[]=300').srcSet, is impossible, because compiling of Pug template occur early then processing of images and require() in Pug returns only a string, not an object.

- const responsiveImage = require('image.jpg?placeholder=true&sizes[]=100,sizes[]=200,sizes[]=300')
img(srcset=responsiveImage.srcSet)

The responsiveImage.srcSet is null because the responsiveImage is not an object in Pug.

This is not a problem of responsive-loader, you can not fix it in the responsive-loader.

Solution

Using the pug-plugin is now possible to get the property srcSet from:

require('image.jpg?sizes[]=100,sizes[]=200,sizes[]=300')

When used the query parameter sizes then the pug-plugin returns the property srcSet from the object. To extract any single property from object, I added supports for the query parameter prop=PROP_NAME.

Usage example in Pug (using pug-plugin):

- const imageSrc = require('./image.jpg?size=300&format=webp')
- const imageSrcSet = require('image.jpg?sizes[]=100,sizes[]=200,sizes[]=300&format=webp')
- const placeholder = require('./image.jpg?prop=placeholder&emitFile=false&placeholder=true&placeholderSize=50')
- const width = require("./image.jpg?prop=width&emitFile=false")
- const height = require("./image.jpg?prop=height&emitFile=false")

div(style=`background-image: url(${placeholder}); width:${width}px; height:${height}px; background-size:cover;`)
  img(src=imageSrc srcset=imageSrcSet)

Suggestion

In the readme of your loader is only usage example with React and JavaScript. But many developers use Pug with responsive-loader. It would be nice to have a documentation for Pug too.

I have already written the documentation and made a demo: How to use responsive-loader with Pug. This documentation contains the reference link to responsive-loader.

Possible would be very useful to place the link to this documentation in your readme.

dazuaz commented 2 years ago

Just updated the readme with a section for examples. Please feel free to suggest edits for it, as I think having this section is a great idea for all the issues that generally come with all the different built pipelines. Thanks!

webdiscus commented 2 years ago

@dazuaz Thank you!