Dynamically Import Images
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
Section titled Recipe- Create a new
assets
folder under thesrc
directory and add your images inside that new folder.
Répertoiresrc/
Répertoireassets/
- avatar-1.jpg
- avatar-2.png
- avatar-3.jpeg
-
Create a new Astro component for your card and import the
<Image />
component.src/components/MyCustomCardComponent.astro ---import { Image } from 'astro:assets';--- -
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.src/components/MyCustomCardComponent.astro ---import { Image } from 'astro:assets';interface Props {imagePath: string;altText: string;name: string;age: number;}const { imagePath, altText, name, age } = Astro.props;--- -
Create a new
images
variable and use theimport.meta.glob
function which returns an object of all of the image paths inside theassets
folder.src/components/MyCustomCardComponent.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('/src/assets/*.{jpeg,jpg,png,gif}')--- -
Use the props to create the markup for your card component.
src/components/MyCustomCardComponent.astro ---import { Image } from 'astro:assets';interface Props {imagePath: string;altText: string;name: string;age: number;}const { imagePath, altText, name, age } = Astro.props;// Type: Record<string, () => Promise<{default: ImageMetadata}>>const images = import.meta.glob('/src/assets/*.{jpeg,jpg,png,gif}')---<div class="card"><h2>{name}</h2><p>Age: {age}</p><Image src={} alt={altText} /></div> -
Inside the
src
attribute, pass in theimages
object and use bracket notation for the image path. Then make sure to invoke the glob function.src/components/MyCustomCardComponent.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('/src/assets/*.{jpeg,jpg,png,gif}')---<div class="card"><h2>{name}</h2><p>Age: {age}</p><Image src={images[imagePath]()} alt={altText} /></div>
-
Import and use the card component inside an Astro page, passing in the values for the
props
.src/pages/index.astro ---import MyCustomCardComponent from '../components/MyCustomCardComponent.astro';---<MyCustomCardComponentimagePath="/src/assets/avatar-1.jpg"altText="A headshot of Priya against a brick wall background."name="Priya"age={25}/>
Plus de méthodes
-
Partage d'État
Apprenez à partager l'état entre les composants du framework avec les Nano Stores.
-
Ajouter un flux RSS
Ajoutez un flux RSS à votre site Astro pour permettre aux utilisateurs de s'abonner à votre contenu.
-
Installation d'un plugin Vite ou Rollup
Découvrez comment vous pouvez importer des données YAML en ajoutant un plugin Rollup à votre projet.
-
Créer un composant image personnalisé
Apprendre à construire un composant image personnalisé qui supporte les requêtes média en utilisant la fonction getImage.
-
Construire des formulaires avec des routes API
Apprendre à utiliser JavaScript pour envoyer les soumissions de formulaires à une route API.
-
Créer des formulaires HTML dans Astro Pages
Apprenez à construire des formulaires HTML et à gérer les soumissions dans votre frontmatter.
-
Use Bun with Astro
Learn how to use Bun with your Astro site.
-
Call endpoints from the server
Learn how to call endpoints from the server in Astro.
-
Vérifier un Captcha
Apprenez à créer une route API et à la récupérer auprès du client.
-
Construisez votre site Astro avec Docker
Apprendre à construire votre site Astro en utilisant Docker.
-
Dynamically Import Images
Learn how to dynamically import images using Vite's import.meta.glob function
-
Ajouter des icônes aux liens externes
Apprendre à installer un plugin rehype pour ajouter des icônes aux liens externes dans vos fichiers Markdown.
-
Add i18n features
Use dynamic routing and content collections to add internationalization support to your Astro site.
-
Ajouter l'heure de la dernière modification
Construire un plugin Remark pour ajouter l'heure de la dernière modification à votre Markdown et MDX.
-
Ajout du temps de lecture
Construire un plugin remark pour ajouter le temps de lecture à vos fichiers Markdown ou MDX.
-
Partage d'état entre composants Astro
Apprendre à partager des états entre composants Astro avec Nano Stores.
-
Utilisation de la diffusion en continu pour améliorer les performances des pages
Apprendre à utiliser la diffusion en continu pour améliorer les performances des pages.
-
Styliser le rendu Markdown avec la typographie Tailwind
Apprenez à utiliser @tailwind/typography pour styliser votre rendu Markdown.