数学
¥Math
本指南探讨如何在 MDX 中支持数学 (LaTeX)。 MDX 支持标准 Markdown 语法 (CommonMark)。这意味着默认情况下不支持数学。可以使用 remark 插件启用数学:remark-math
,结合 rehype 插件:rehype-katex
(KaTeX) 或 rehype-mathjax
(MathJax)。与其他 remark 和 rehype 插件一样,它们可以在 分别在 ProcessorOptions
中的 remarkPlugins
和 rehypePlugins
中传递。有关插件的更多信息可在 § 扩展 MDX 中找到
¥This guide explores how to support math (LaTeX) in MDX. MDX supports standard markdown syntax (CommonMark). That means math is not supported by default. Math can be enabled by using a remark plugin: remark-math
, combined with a rehype plugin: either rehype-katex
(KaTeX) or rehype-mathjax
(MathJax). Like other remark and rehype plugins, they can be passed in remarkPlugins
and rehypePlugins
, respectively, in ProcessorOptions
. More info on plugins is available in § Extending MDX
假设我们有一个像这样的 MDX 文件:
¥Say we have an MDX file like this:
# $$\sqrt{a^2 + b^2}$$
上面带有数学的 MDX 可以使用以下模块进行转换:
¥The above MDX with math can be transformed with the following module:
import fs from 'node:fs/promises'
import {compile} from '@mdx-js/mdx'
import rehypeKatex from 'rehype-katex'
import remarkMath from 'remark-math'
console.log(
String(
await compile(await fs.readFile('example.mdx'), {
rehypePlugins: [rehypeKatex],
remarkPlugins: [remarkMath]
})
)
)
Expand equivalent JSX
<>
<h1>
<span className="katex">
<span className="katex-mathml">
<math xmlns="http://www.w3.org/1998/Math/MathML">…</math>
</span>
<span className="katex-html" aria-hidden="true">
…
</span>
</span>
</h1>
</>
重要的:如果你选择 rehype-katex
,你还应该在页面上的某个位置使用 katex.css
以正确设置数学样式。在撰写本文时,最后一个版本是:
¥Important: if you chose rehype-katex
, you should also use katex.css
somewhere on the page to style math properly. At the time of writing, the last version is:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">
要获取样式表的最新链接,请转到 katex docs
。
¥To get the latest link to the stylesheet, go to katex docs
.
注意:另请参阅 remark-mdx-math-enhanced
,你可以使用它来支持数学内部的 JavaScript 表达式(例如访问属性或进行计算)
¥Note: see also remark-mdx-math-enhanced
, which you can use to support JavaScript expressions inside of math (such as to access properties or to make calculations)