本文解释了如何扩展 MDX 内容,具体来说,如何使用插件转换内容。请参阅 § 使用 MDX 了解如何传递组件、props 和布局。请参阅 § 入门指南 了解如何将 MDX 集成到您的项目中。
组件与插件
在使用 @mdx-js/mdx
或其集成之一时,有三个扩展点:
- 传递给编译器的选项(请参阅
@mdx-js/mdx
中的 API) - 插件,可以钩入编译的多个阶段(请参阅remark 插件,rehype 插件,以及新的 recma 插件)
- 在运行时传递、定义或导入的组件(请参阅§ 使用 MDX)
大多数情况下,这些组件和插件与 MDX 并不直接关联。例如,如果您使用 React,则可以在 MDX 中使用 ReactConfetti
。或者,您可以使用插件 remark-gfm
来在 MDX 中启用 GFM 功能。有时,我们需要特定的组件或插件来与 MDX 一起工作。我们将它们编译到这里。
组件列表
PaulieScanlon/mdx-embed
— 用于嵌入第三方内容的 React 组件,与 MDX 提供程序集成system-ui/theme-ui
— 用于构建一致性应用程序的 React 组件,与 MDX 提供程序集成
注意: 有另一个特定于 MDX 的组件吗?请发送 PR 将其添加到这里!
插件列表
另请参阅 remark 插件列表 和 rehype 插件列表。
remcohaszing/recma-export-filepath
— 导出文件路径ipikuka/recma-mdx-change-props
— 在_createMdxContent
函数中将参数更改为_props
domdomegg/recma-mdx-displayname
— 为MDXContent
组件添加displayName
,以便在生产环境中切换ipikuka/recma-mdx-escape-missing-components
— 对于缺少的组件,设置默认值为() => null
,而不是抛出错误remcohaszing/recma-mdx-is-mdx-component
— 在 MDX 组件上添加一个isMdxComponent
字段remcohaszing/recma-nextjs-static-props
— 生成 Next.js 中暴露顶级标识符的getStaticProps
remcohaszing/rehype-mdx-code-props
— 将代码的meta
字段解释为 JSX propsremcohaszing/rehype-mdx-import-media
— 将媒体源更改为 JavaScript 导入remcohaszing/rehype-mdx-title
— 将页面标题暴露为字符串pangelani/remark-mdx-chartjs
— 使用react-chartjs-2
将围栏代码块替换为图表remcohaszing/remark-mdx-frontmatter
— 将前置数据(YAML)元数据更改为导出goodproblems/remark-mdx-math-enhanced
— 使用其中的 JavaScript 增强数学功能
注意: 有另一个特定于 MDX 的统一插件吗?请发送 PR 将其添加到这里!
使用插件
在插件名称中编码了传递插件的位置:remark 插件放在 ProcessorOptions
的 remarkPlugins
中,rehype 插件放在 rehypePlugins
中。这些字段期望插件列表和/或 [plugin, options]
的列表:
TypeScript
import {compile} from '@mdx-js/mdx'
import rehypeKatex from 'rehype-katex' // 使用 KaTeX 渲染数学公式。
import remarkFrontmatter from 'remark-frontmatter' // YAML 和类似的。
import remarkGfm from 'remark-gfm' // 表格、脚注、删除线、任务列表、文字 URL。
import remarkMath from 'remark-math' // 支持像 `$so$` 这样的数学公式。
const file = '# hi'
// 一个插件:
await compile(file, {remarkPlugins: [remarkGfm]})
// 一个带有选项的插件:
await compile(file, {remarkPlugins: [[remarkFrontmatter, 'toml']]})
// 两个插件:
await compile(file, {remarkPlugins: [remarkGfm, remarkFrontmatter]})
// 两个插件,第一个带有选项:
await compile(file, {remarkPlugins: [[remarkGfm, {singleTilde: false}], remarkFrontmatter]})
// remark 和 rehype 插件:
await compile(file, {rehypePlugins: [rehypeKatex], remarkPlugins: [remarkMath]})
// remark 和 rehype 插件,最后一个带有选项:
await compile(file, {
// 一个带有选项的插件:
rehypePlugins: [[rehypeKatex, {strict: true, throwOnError: true}]],
remarkPlugins: [remarkMath]
})
创建插件
为 MDX 创建插件与为 remark 或 rehype 创建插件基本相同。关于这方面的几篇指南和教程在 § 在 unifiedjs.com
上学习。
有关插件的 MDX 特定部分,请阅读 ¶ 架构 以了解 @mdx-js/mdx
的工作原理。有关表示 MDX 特定功能的节点类型的信息,请参阅 ¶ remark-mdx
中的语法树 并使用我们的交互式 § Playground。