Skip to content

Latest commit

 

History

History
155 lines (123 loc) · 5.32 KB

dynamically-importing-images.mdx

File metadata and controls

155 lines (123 loc) · 5.32 KB
title description i18nReady type
Dynamically import images
Learn how to dynamically import images using Vite's import.meta.glob function.
true
recipe

import { Steps } from '@astrojs/starlight/components'; import { FileTree } from '@astrojs/starlight/components';

Local images must be imported into .astro files in order to display them. There will be times where you will want or need to dynamically import the image paths of your images instead of explicitly importing each individual image.

In this recipe, you will learn how to dynamically import your images using Vite's import.meta.glob function. You will build a card component that displays the name, age, and photo of a person.

Recipe

1. Create a new `assets` folder under the `src` directory and add your images inside that new folder.
<FileTree>
- src/
  - assets/
    - avatar-1.jpg
    - avatar-2.png
    - avatar-3.jpeg
</FileTree>

:::note
`assets` is a popular folder name convention for placing images but you are free to name the folder whatever you like.
::: 
  1. Create a new Astro component for your card and import the <Image /> component.

    ---
    import { Image } from 'astro:assets';
    ---
  2. Specify the props that your component will receive in order to display the necessary information on each card. You can optionally define their types, if you are using TypeScript in your project.

    ---
    import { Image } from 'astro:assets';
    
    interface Props {
       imagePath: string;
       altText: string;
       name: string;
       age: number;
    }
    
    const { imagePath, altText, name, age } = Astro.props;
    ---
  3. Create a new images variable and use the import.meta.glob function which returns an object of all of the image paths inside the assets folder. You will also need to import ImageMetadata type to help define the type of the images variable.

    ---
    import type { ImageMetadata } from 'astro';
    import { Image } from 'astro:assets';
    
    interface Props {
       imagePath: string;
       altText: string;
       name: string;
       age: number;
    }
    
    const { imagePath, altText, name, age } = Astro.props;
    const images = import.meta.glob<{ default: ImageMetadata }>('/src/assets/*.{jpeg,jpg,png,gif}')
    ---
  4. Use the props to create the markup for your card component.

    ---
    import type { ImageMetadata } from 'astro';
    import { Image } from 'astro:assets';
    
    interface Props {
       imagePath: string;
       altText: string;
       name: string;
       age: number;
    }
    
    const { imagePath, altText, name, age } = Astro.props;
    const images = import.meta.glob<{ default: ImageMetadata }>('/src/assets/*.{jpeg,jpg,png,gif}');
    ---
    <div class="card">
        <h2>{name}</h2>
        <p>Age: {age}</p>
        <Image src={} alt={altText} />
    </div>
  5. Inside the src attribute, pass in the images object and use bracket notation for the image path. Then make sure to invoke the glob function.

    Since you are accessing the images object which has an unknown type, you should also throw an error in case an invalid file path is passed as a prop.

    ---
    import type { ImageMetadata } from 'astro';
    import { Image } from 'astro:assets';
    
    interface Props {
       imagePath: string;
       altText: string;
       name: string;
       age: number;
    }
    
    const { imagePath, altText, name, age } = Astro.props;
    const images = import.meta.glob<{ default: ImageMetadata }>('/src/assets/*.{jpeg,jpg,png,gif}');
    if (!images[imagePath]) throw new Error(`"${imagePath}" does not exist in glob: "src/assets/*.{jpeg,jpg,png,gif}"`);
    ---
    <div class="card">
        <h2>{name}</h2>
        <p>Age: {age}</p>
        <Image src={images[imagePath]()} alt={altText} />
    </div>

    :::note images is an object that contains all of the image paths inside the assets folder.

    const images = {
      './assets/avatar-1.jpg': () => import('./assets/avatar-1.jpg'),
      './assets/avatar-2.png': () => import('./assets/avatar-2.png'),
      './assets/avatar-3.jpeg': () => import('./assets/avatar-3.jpeg')
    }

    The imagePath prop is a string that contains the path to the image that you want to display. The import.meta.glob() is doing the work of finding the image path that matches the imagePath prop and handling the import for you. :::

  6. Import and use the card component inside an Astro page, passing in the values for the props.

    ---
    import MyCustomCardComponent from '../components/MyCustomCardComponent.astro';
    ---
    <MyCustomCardComponent 
        imagePath="/src/assets/avatar-1.jpg"
        altText="A headshot of Priya against a brick wall background."
        name="Priya"
        age={25}
    />