动态导入图片
本地 images 必须导入到 .astro
文件中才能显示。有时你会想要或需要动态导入图片的图片路径,而不是显式导入每个单独的图片。
¥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.
在本教程中,你将学习如何使用 Vite 的 import.meta.glob
功能动态导入图片。你将构建一个显示人员名称、年龄和照片的卡片组件。
¥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
-
Create a new
assets
folder under thesrc
directory and add your images inside that new folder.Directorysrc/
Directoryassets/
- avatar-1.jpg
- avatar-2.png
- avatar-3.jpeg
-
Create a new Astro component for your card and import the
<Image />
component. -
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. -
Create a new
images
variable and use theimport.meta.glob
function which returns an object of all of the image paths inside theassets
folder. You will also need to importImageMetadata
type to help define the type of theimages
variable. -
Use the props to create the markup for your card component.
-
Inside the
src
attribute, pass in theimages
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 alsothrow
an error in case an invalid file path is passed as a prop. -
Import and use the card component inside an Astro page, passing in the values for the
props
.