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

如何让Astro项目识别多个Markdown文件目录?

Astro多目录MD转HTML构建报错解决

问题说明

基于Astro的单目录MD转HTML示例项目扩展,在src/content下新增第二个子目录后,执行npm run build时触发路由匹配错误,错误信息如下:

> npm run build

 generating static routes 
▶ src/pages/index.astro
  └─ /index.html (+14ms)
▶ src/pages/docs/[slug].astro
 error   Expected "slug" to match "[^\/#\?]+?", but got "console-apps/autoclientcreation"
  File:
    C:\Dev2\Documentation4\content-collecttion-api-example-main\node_modules\path-to-regexp\dist\index.js:229:27
  Code:
    228 |                 if (validate && !matches[i].test(segment)) {
    > 229 |                     throw new TypeError("Expected \"".concat(token.name, "\" to match \"").concat(token.pattern, "\", but got \"").concat(segment, "\""));
          |                           ^
      230 |                 }
      231 |                 path += token.prefix + segment + token.suffix;
      232 |   

核心原因是原路由src/pages/docs/[slug].astro中的[slug]仅支持匹配无斜杠的单段路径,新增子目录后,MD文件的slug会带上目录层级的斜杠(如console-apps/autoclientcreation),超出了默认路由的匹配规则。

解决步骤

1. 修改路由为通配符格式

将src/pages/docs/[slug].astro重命名为src/pages/docs/[...slug].astro。[...slug]是Astro的通配符路由,可匹配包含斜杠的多段路径,完美适配带目录层级的slug。

2. 调整内容查询逻辑

打开修改后的[...slug].astro,调整内容获取代码,确保能正确匹配所有带层级的MD文件:

---
import { getCollection } from 'astro:content';

export async function getStaticPaths() {
  // 获取目标集合下的所有MD内容,若有多个集合可合并结果
  const allDocs = await getCollection('docs');
  // 多集合示例:
  // const newsletterDocs = await getCollection('newsletter');
  // const consoleAppDocs = await getCollection('console-apps');
  // const allDocs = [...newsletterDocs, ...consoleAppDocs];

  return allDocs.map(doc => ({
    params: { slug: doc.slug },
    props: { doc },
  }));
}

const { doc } = Astro.props;
const { Content } = await doc.render();
---
<article>
  <h1>{doc.data.title}</h1>
  <Content />
</article>

3. 确认内容集合配置

检查src/content/config.ts,确保已正确注册所有MD目录对应的集合:

import { defineCollection, z } from 'astro:content';

// 定义集合通用schema
const baseSchema = z.object({
  title: z.string(),
  // 可添加其他必填字段
});

export const collections = {
  docs: defineCollection({ schema: baseSchema }),
  newsletter: defineCollection({ schema: baseSchema }),
  'console-apps': defineCollection({ schema: baseSchema }),
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:05:26