juliomrqz / nuxt-optimized-images

🌅🚀 Automatically optimizes images used in Nuxt.js projects (JPEG, PNG, SVG, WebP and GIF).
https://marquez.co/docs/nuxt-optimized-images/
MIT License
842 stars 30 forks source link

Srcset not properly loading #341

Closed mattkaye closed 2 years ago

mattkaye commented 2 years ago

I'm using the responsive library with sharp and only the first srcset image is being loaded. My image tags are being wrapped in vue-lazyload. I'm also using the lqip-loader library

My nuxt config:

optimizedImages: {
  optimizeImages: 1,
  optimizeImagesInDev: 1,
  handleImages: ["jpeg", "png", "webp", "gif"],
  responsive: {
    adapter: require("responsive-loader/sharp"),
    sizes: [640, 960, 1200],
  },
},

Just adding a test image:

<div v-lazy-container="{ selector: 'img' }">
  <img
    :data-src="require('~/assets/images/foo.jpg')"
    :data-loading="require('~/assets/images/foo.jpg?lqip')"
    :srcSet="require('~/assets/images/foo.jpg?resize')"
  />
</div>

And I get this after the build: <img data-src="/_nuxt/assets/images/large-test--fa25911.jpg" data-loading="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAA......." srcset="/_nuxt/assets/images/foo--640--78624a0.jpg" src="/_nuxt/assets/images/large-test--fa25911.jpg" lazy="loaded">

Notice the srcset only ever produces the first image. Always the first in the array from nuxt.config.js Also if I removed the config settings from nuxt config and inline it, I get the same result, IE:

require('~/assets/images/foo.jpg?resize&sizes[]=300&sizes[]=600&sizes[]=1000')

The relevant libraries from package.json:

"vue-lazyload": "^1.3.3",
"lqip-loader": "^2.2.1",
"sharp": "^0.29.1",
"@aceforth/nuxt-optimized-images": "^1.4.0",
"imagemin-mozjpeg": "^9.0.0",
gekkedev commented 2 years ago

The first image being returned is because ?resize will always give you a sourceset but wraps it in an object. When you don't call a specific property, it internally calls toString() and just returns the first image - that's how responsive-loader works. You could report it as bug there but the documentation presents this as the expected result. To fix your issue and return all images into the srcSet attribute, simply change

:srcSet="require('~/assets/images/foo.jpg?resize')"

into

:srcSet="require('~/assets/images/foo.jpg?resize').srcSet"

When you take a closer look at the other properties, you might also find additional values except for the srcSet string like width and height which improve your layout stability when dealing with placeholders. :wink:

mattkaye commented 2 years ago

@gekkedev ahh you're correct. I see it in the docs now. Man, that's an easy one to miss, hence my missing it 👎 Anyway thank you for getting around to answering this!