Niels-IO / next-image-export-optimizer

Use Next.js advanced <Image/> component with the static export functionality. Optimizes all static images in an additional step after the Next.js static export.
413 stars 51 forks source link

Export utilities from ExportedImage component #210

Open jack828 opened 4 months ago

jack828 commented 4 months ago

Hello, thank you for the great library. I'm using it with great success on cloudflare pages using next-on-pages.

I have a situation where I want to use optimised images from this library outside of react components - specifically, in nextjs' dynamic metadata. My use case is using remote images, but i'm sure for local ones there's a better way too.

After simply lifting out the functions imageURLForRemoteImage, urlToFilename (available in dist/utils), generateImageUrl, and splitFilePath into my project, i can mock something up like so:

In a app router page, e.g. src/app/foo/page.tsx

const imageURLForRemoteImage // as in ExportedImage
const urlToFilename // as in ExportedImage
const generateImageUrl // as in ExportedImage
const splitFilePath // as in ExportedImage

export async function generateMetadata(
  { params }: PageProps,
  parent: ResolvingMetadata
): Promise<Metadata> {
  const item = items[params.id]
  return {
    title: item.title,
    openGraph: {
      images: [imageURLForRemoteImage({ src: item.images.cover /* a remote image i.e. https://example.com/foo.jpg */, width: 256 })]
    }
  }
}

This works as expected (thankfully) and outputs the correct optimised URL.

I suppose the question is either:

Thanks again!

Niels-IO commented 2 months ago

Hi @jack828,

Interesting approach! I haven't thought about this use case yet. I have to look into it, how and if exporting these functions is a good idea. Currently, these are internal helpers.