Skip to navigation

Frontmatter

本指南探讨如何在 MDX 中支持 YAML frontmatter。 MDX 支持标准 Markdown 语法 (CommonMark)。这意味着默认情况下不支持 frontmatter。

¥This guide explores how to support YAML frontmatter in MDX. MDX supports standard markdown syntax (CommonMark). That means frontmatter is not supported by default.

MDX 提供了 Frontmatter 的强大且动态的替代方案,即 ESM (import/export)。这些导出:

¥MDX comes with a powerful and dynamic alternative to frontmatter, namely ESM (import/export). These exports:

example.mdx
export const name = 'World'
export const title = 'Hi, ' + name + '!'

# {title}

可以像这样使用:

¥Can be used like so:

example.js
import * as Post from './example.mdx' // Assumes an integration is used to compile MDX -> JS.

console.log(Post.title) // Prints 'Hi, World!'

不过,你可能更喜欢 frontmatter,因为它允许你定义可以在编译之前从文件系统中提取的数据。假设我们的 MDX 和 frontmatter 看起来像这样:

¥You might prefer frontmatter though, as it lets you define data that can be extracted from the file system before compiling. Say our MDX with frontmatter looked like this:

example.mdx
---
title: Hi, World!
---

# Hi, World!

然后无需编译或评估元数据就可以像这样访问:

¥Then without compiling or evaluating the metadata can be accessed like so:

example.js
import {read} from 'to-vfile'
import {matter} from 'vfile-matter'

const file = await read('example.mdx')
matter(file)

console.log(file.data.matter)

我们的编译器 @mdx-js/mdx 默认情况下不理解 YAML frontmatter,但可以通过使用注释插件 remark-frontmatter 来启用它:

¥Our compiler, @mdx-js/mdx, doesn’t understand YAML frontmatter by default but it can be enabled by using a remark plugin, remark-frontmatter:

example.js
import fs from 'node:fs/promises'
import {compile} from '@mdx-js/mdx'
import remarkFrontmatter from 'remark-frontmatter'

const file = await compile(await fs.readFile('example.mdx'), {
  remarkPlugins: [remarkFrontmatter]
})

console.log(file)

现在它“起作用了”。frontmatter 不会像 Markdown 一样渲染。但嵌入在 frontmatter 中的数据无法从 MDX 内部获得。如果我们也想要那样怎么办?就像这样:

¥Now it “works”. The frontmatter is not rendered as if it was markdown. But the data embedded in the frontmatter isn’t available from inside the MDX. What if we wanted that too? Like so:

example.mdx
---
title: Hi, World!
---

# {title}

这正是 remark 插件 remark-mdx-frontmatter 的作用。

¥That’s exactly what the remark plugin remark-mdx-frontmatter does.

该插件与所有 remark 插件一样,可以作为 remarkPluginsProcessorOptions 传递。有关插件的更多信息可在 § 扩展 MDX 中找到

¥That plugin, like all remark plugins, can be passed as remarkPlugins in ProcessorOptions. More info on plugins is available in § Extending MDX

MDX 中文网 - 粤ICP备13048890号