提问人:Artmole 提问时间:5/27/2023 更新时间:5/27/2023 访问量:126
如何正确地将 markdown frontmatter 中定义的图像列表导入到 astro 布局中?
How can I correctly import a list of images defined in markdown frontmatter into an astro layout?
问:
我正在用 Astro 构建一个作品集网站,每个项目都有一个对象,其中的 markdown frontmatter 中定义了媒体,如下所示:
media:
- text: "descriptive text about first cluster of images"
paths: ["../images/projects/project_1/img_0.png","../images/projects/project_1/img_1.png","../images/projects/project_1/img_2.png"]
- text: "descriptive text about second cluster of images"
paths: ["../images/projects/project_1/img_3.png","../images/projects/project_1/img_4.png","../images/projects/project_1/img_5.png"]
- text: "descriptive text about third cluster of images"
paths: ["../images/projects/project_1/img_8.png"]
有一个 所有图像都存储在 src/images/projects/project_x/y.png 中
imageContainer.astro 如下所示:
...
<div class={image-section}>
{mediaItem.paths.map((path: string) =>
<div class="image-container">
<img src={path} alt="cool images about stuff"/>
</div>
)}
</div>
...
我在构建时收到以下错误(为了便于阅读,我重命名了上面和下面的代码中的路径,因此这里的路径不是一对一的):
generating static routes
▶ src/pages/index.astro
error Cannot find module 'C:\Users\Niko\Creative\Programming\web\astro\portfolio_v1\dist\chunks\images\projects\project_1\img_1.png' imported from C:\Users\Niko\Creative\Programming\web\astro\portfolio_v1\dist\chunks\pages\all.87c76733.mjs
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Niko\Creative\Programming\web\astro\portfolio_v1\dist\chunks\images\projects\project_1\img_1.png' imported from C:\Users\Niko\Creative\Programming\web\astro\portfolio_v1\dist\chunks\pages\all.87c76733.mjs
当我运行时,一切正常,但是当我构建时,只有显示。那么,在构建时,如何让布局从 Markdown frontmatter 中定义的对象正确导入列出的图像呢?npm run dev
alt-text
我已经尝试在布局的 JavaScript/TypeScript 部分制作一个解决方法导入语句,在其中我将源映射到导入的路径,如下所示:
let sources : Record<string, string> = {};
for (let index = 0; index < mediaItem.paths.length; index++) {
const element : any = mediaItem.paths[index];
let source = ((await import(element)).default);
sources[element] = source;
}
然后将对象用作字典,如下所示:
...
<div class={image-section}>
{mediaItem.paths.map((path: string) =>
<div class="image-container">
<img src={sources[path]} alt="cool images about stuff"/>
</div>
)}
</div>
...
这有效但未构建。并给出了与上述相同的错误。npm run dev
答: 暂无答案
评论