You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Astro中如何将Markdown文件与关联资源同目录存放?

能否在Astro中将Markdown/MDX与关联资源放在同一文件夹?

完全可以,Astro的**内容集合(Content Collections)**特性原生支持这种“单篇内容+资源同文件夹”的结构,完美替代将资源存放在public目录、反复回退路径引用的方式。

具体实现步骤:

  1. 配置内容集合
    在src/content/config.ts中定义你的内容集合(以posts为例),指定文件类型为mdx或markdown:

    import { defineCollection, z } from 'astro:content';
    
    const posts = defineCollection({
      type: 'content',
      schema: z.object({
        title: z.string(),
        date: z.date(),
      }),
    });
    
    export const collections = { posts };
    
  2. 按期望结构组织文件
    直接采用你想要的目录结构,将MDX文件和关联资源放在同一子文件夹下:

    src/
        content/
            posts/
                post1/
                    post1.mdx
                    image1-in-post1.png
                    image2-in-post1.png
    

    注:如果仍在使用旧版的src/posts目录而非src/content,Astro同样支持这种同文件夹资源引用,只是内容集合是当前推荐的最佳实践。

  3. 在MDX中引用资源
    两种常用引用方式:

    • 直接用Markdown图片语法,使用相对路径:
      ![文章配图1](./image1-in-post1.png)
      
    • 导入资源后通过Astro的<Image>组件使用(支持自动优化):
      import Image1 from './image1-in-post1.png';
      import { Image } from 'astro:assets';
      
      <Image src={Image1} alt="文章配图1" />
      

这种结构的优势很明显:资源与内容紧密绑定,便于单篇内容的迁移和管理,无需记忆冗长的回退路径,同时Astro会自动处理资源的打包、压缩和格式优化。

内容的提问来源于stack exchange,提问作者emg184

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:10:23