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

如何在React.js中使用frontmatter-markdown提取MD文件数据?

提取Markdown文件Frontmatter数据的解决方案

先修复Frontmatter格式问题

你的Markdown文件里的Frontmatter存在格式错误,这是解析失败的核心原因:

  • 第一个Frontmatter块有多余缩进,且键值对末尾加了逗号(YAML规范不需要逗号)
  • 第二个块没有用---包裹,这是识别Frontmatter的必要标识
  • 末尾的空代码块会干扰解析逻辑

修正后的正确格式:

---
title: "API"
description: "Restful API"
category: "API"
slug: "handle-with-api"
path: "../articles/api-concept.md"
---

---
title: "ah"
description: "sdsdds"
category: "API"
slug: "handle-with-sdsdsd"
path: "../articles/dsdsd-concept.md"
---

配置frontmatter-markdown-loader

在webpack配置文件中添加对应loader规则:

module.exports = {
  module: {
    rules: [
      {
        test: /\.md$/,
        use: [
          {
            loader: 'frontmatter-markdown-loader',
            options: {
              mode: ['react'] // 按需选择模式,也可设为['frontmatter']仅提取元数据
            }
          }
        ]
      }
    ]
  }
};

在项目中调用提取的数据

导入Markdown文件后,直接访问frontmatter属性即可拿到数据:

import targetFile from './file.md';

// 打印提取到的Frontmatter内容
console.log(targetFile.frontmatter.title);
console.log(targetFile.frontmatter.category);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:25:21