动态导入图像
本地图片必须导入到 .astro
文件中才能显示。有时,你可能想要或需要动态导入图片的路径,而不是显式地逐个导入每张图片。
在本指南中,你将学习如何使用 Vite 的 import.meta.glob
函数动态导入图片。你将构建一个卡片组件,用于显示人物的姓名、年龄和照片。
-
在
src
目录下创建一个新的assets
文件夹,并将你的图片添加到这个新文件夹中。目录src/
目录assets/
- avatar-1.jpg
- avatar-2.png
- avatar-3.jpeg
assets
是一个用于放置图片的流行文件夹命名约定,但你也可以随意命名该文件夹。 -
为你的卡片创建一个新的 Astro 组件,并导入
<Image />
组件。src/components/MyCustomCardComponent.astro ---import { Image } from 'astro:assets';--- -
指定你的组件将接收的
props
,以便在每个卡片上显示必要的信息。如果你的项目中使用 TypeScript,你还可以选择性地定义它们的类型。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;--- -
创建一个新的
images
变量,并使用import.meta.glob
函数,它会返回assets
文件夹中所有图片路径组成的对象。你还需要导入ImageMetadata
类型来帮助定义images
变量的类型。src/components/MyCustomCardComponent.astro ---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}')--- -
使用 props 为你的卡片组件创建标记。
src/components/MyCustomCardComponent.astro ---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> -
在
src
属性中,传入images
对象,并对图片路径使用方括号表示法。然后确保调用 glob 函数。由于你正在访问类型未知的
images
对象,当一个无效的文件路径作为 prop 传入时,你应该throw
一个错误。src/components/MyCustomCardComponent.astro ---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>images
是一个包含assets
文件夹中所有图片路径的对象。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')}imagePath
prop 是一个字符串,包含你想要显示的图片的路径。import.meta.glob()
会负责查找与imagePath
prop 匹配的图片路径并为你处理导入。 -
在 Astro 页面中导入并使用卡片组件,并传入
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}/>