#Dynamic image source import via props

4 messages · Page 1 of 1 (latest)

covert otter
#

Sorry, I feel like I am asking the same question over and over again but I can't wrap my head around how the Image component works.

I am trying to create a Hero component that I can pass a source path as a prop to render different images therefore I think I need dynamic imports.

When I pass a string with the source path to the Image component everything works fine on my dev server and during build.

        <Image
          src={(await import("../images/hero.jpg")).default}
          alt=""
          width={1920}
          height={1920}
        />

When I set up a prop in my component it still works on my dev server but the build fails.

interface Props {
  src: string;
}

const { src } = Astro.props;
        <Image
          src={(await import(src)).default}
          alt=""
          width={1920}
          height={1920}
        />
Cannot find module '/Users/hrvstr/Developer/volpp-kuechen/dist/chunks/images/hero.jpg' imported from /Users/hrvstr/Developer/volpp-kuechen/dist/chunks/pages/all.f2222cd9.mjs
covert warren
#

Every import need to be statically analysable, so the later doesn't work because src is dynamic

covert otter
#

Okay, so I can't create a dynamic Hero component that I can pass a path to?

<Hero src="../images/hero.jpg" />

I would need to use a slot for the Image component like this:

<Hero>
  <Image src="..." />
</Hero>
covert otter
#

I got it halfway working now. It seems like it's expecting a file extension. Not perfect but should do the trick for now.

        <Image
          src={import(`../images/heros/${image}.jpg`)}
          alt=""
          width={1920}
          height={1920}
          class="h-full w-full object-cover"
        />