import {Note} from '../_component/note.server.js'
export const navSortSelf = 3
export const info = {
  author: [
    {name: 'Titus Wormer', github: 'wooorm', twitter: 'wooorm'}
  ],
  published: new Date('2021-10-06'),
  modified: new Date('2022-02-01')
}

# Math

This guide explores how to support math (LaTeX) in MDX. {/* more */}
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`][remark-math],
combined with a rehype plugin: either
[`rehype-katex`][rehype-katex] (KaTeX) or [`rehype-mathjax`][rehype-mathjax]
(MathJax).
remark plugins can be passed in
[`options.remarkPlugins`][options-remark-plugins] and rehype
plugins in [`options.rehypePlugins`][options-rehype-plugins].
More info on plugins is available in [§ Extending MDX][extend]

Say we have an MDX file like this:

```mdx path="example.mdx"
# $\sqrt{a^2 + b^2}$
```

The above MDX with math can be transformed with the following module:

```js path="example.js"
import {promises as fs} from 'node:fs'
import {compile} from '@mdx-js/mdx'
import rehypeKatex from 'rehype-katex'
import remarkMath from 'remark-math'

main()

async function main() {
  console.log(
    String(
      await compile(await fs.readFile('example.mdx'), {
        remarkPlugins: [remarkMath],
        rehypePlugins: [rehypeKatex]
      })
    )
  )
}
```

<details>
  <summary>Expand equivalent JSX</summary>

  ```jsx path="output.jsx"
  <>
    <h1>
      <span className="math math-inline">
        <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>
      </span>
    </h1>
  </>
  ```
</details>

<Note type="important">
  **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:

  ```html
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/katex.min.css" integrity="sha384-RZU/ijkSsFbcmivfdRBQDtwuwVqK7GMOw6IMvKyeWL2K5UAlyp6WonmB8m7Jd0Hn" crossorigin="anonymous">
  ```
</Note>

[commonmark]: https://spec.commonmark.org/current/

[remark-math]: https://github.com/remarkjs/remark-math/tree/main/packages/remark-math

[rehype-katex]: https://github.com/remarkjs/remark-math/tree/main/packages/rehype-katex

[rehype-mathjax]: https://github.com/remarkjs/remark-math/tree/main/packages/rehype-mathjax

[options-remark-plugins]: /packages/mdx/#optionsremarkplugins

[options-rehype-plugins]: /packages/mdx/#optionsrehypeplugins

[extend]: /docs/extending-mdx/
