#Dynamically importing images using slug and filename

6 messages · Page 1 of 1 (latest)

hard galleon
#

Hey I'm following https://docs.astro.build/en/recipes/dynamically-importing-images/

  • My import glob is "/src/assets/**/*.{jpeg,jpg,png,gif}"
  • It works when I pass in the correct path as a prop <Image src={images[href]()} /> when href is /src/assets/my-image.jpg
  • It fails when I pass href as my-image.jpg

BUT I wrap my path as so:

<Image src={images[`/src/assets/${href}`]()} />` // the images cannot be found although the paths are correct

Any tips :hmm:

Docs

Learn how to dynamically import images using Vite's import.meta.glob function.

tropic drum
#

You're already somewhere inside src/, so your path is incorrect. It should probably be something like ../assets/... or ../../assets/...
I suggest you setup an alias, so you can just use @assets/... regardless of where you are in the hierarchy
https://docs.astro.build/en/guides/typescript/#import-aliases

Docs

Learn how to use Astro's built-in TypeScript support.

hard galleon
#

The paths are correct ... I will show the key difference when it breaks:

async function getImageData({ slug }) {
  // this works
  return await images[`/src/assets/${slug}/banner.jpg`]();
}

and fails when i dont return the src as the only value

async function getImageData({ slug }) {
  const src = await images[`/src/assets/${slug}/banner.jpg`]();
  return { src, slug }
}

when I map through ... list.map(({ src }) => (<Image={src} />)
Astro breaks

tropic drum
#

In the first case, you're getting an ImageMetadata object back. In the second case, you're getting {src: ImageMetadata, slug: string} object back. So, you'd have to do: list.map(({ src }) => (<Image={src.src} />)

hard galleon
#

indeed - sorry for not covering that. - its that src.src isnt working either - that was my point.

#

Im not sure whether there is some Astro magic happening that is getting in the way