lorenzodejong / next-sanity-image

Utility for using responsive images hosted on the Sanity.io CDN with the Next.js image component.
MIT License
148 stars 19 forks source link

Is it possible to use this feature as a pure function rather than a hook? #5

Closed judewang closed 3 years ago

judewang commented 3 years ago

Hi, thank you for creating this awesome tool, it saved my time.

According to the return type is UseNextSanityImageProps, I'd wonder if it is possible to run the main function inside getStaticProps ? If that's possible, we won't need to include SanityClient into our front-end bundle, we can get the imageProps within build time or server side. Thanks.

lorenzodejong commented 3 years ago

Thanks for opening an issue!

It seems like the current implementation of next/image makes it hard to do so. In order to load images for each configured device size the component calls the loader callback prop (https://nextjs.org/docs/api-reference/next/image#loader). Since this will both be invoked during SSR and client-side hydration, this library needs to be able to resolve to a URL on the client-side (thus requiring SanityClient).

It would probably be possible to create a function which can be called from getStaticProps which resolves to an array of URL's: values for the srcSet attribute. In turn you could render a custom img element with the provided srcSet values. However you would lose the additional functionality which next/image provides. This library is currently specifically geared towards working with next/image to reduce the API surface.

If you have any additional ideas to potentially support this behavior i'd be happy to hear!