Use Gatsbyjs with MDX and Latex Equations
I am using Gatsbyjs for a while and really love it to generate static sites. With the help of gatsby-transformer-remark
plugin, It is a pleasure to transform Markdown files to HTML. I built a documentation site in production and this blog site for personal use, they both run well and serve their own purposes.
However, the whole content will depend on Markdown syntax, which was invented to be simple. It wasn’t enough for some people, many new features were added to Markdown like flow chart support, latex equation support, table support, etc. While those features are indeed helpful in someway and make it easier to write beautiful document in text format. There is still no Markdown standard and almost every Markdown editor has its own rendering rules.
I chose markdown in the first place for its simplicity. Now I have to bear with markdown file generated in one place may not render correctly in another place, or stick with basic syntax that lack of features I need. Fortunately, MDX comes to the rescue. MDX lets us write JSX embedded inside markdown. It’s a great combination that allows us to use markdown’s terse syntax for the little things and JSX for more advanced components.
I updated my site to use MDX file as template for HTML generation, it works seamlessly as I set it to backwards compatible with md files. The PIA is that it doesn’t support latex out of box. Of course I can transfer latex to html or JSX block then embed it in markdown file. That’s ok for occasionally use but too much for many equations. I couldn’t find a perfect solution for my need and spent some time to make it work.
The goal is when we type latex in a $$ latex $$
block like this in a md or mdx file:
|
|
The following will be rendered in the end:
$$
Mean = \frac{10 + 14+ 7 +23+ 23+ 15 + 7 + 23 + 32}{9} = \frac{154}{9} \approx 17.11
$$
gatsby-plugin-mdx
is the official integration for using MDX with Gatsby.
Install with npm:
|
|
Or install with yarn:
|
|
Then we need remark-math
and rehype-katex
to render math blocks. remark-math
parses math blocks and rehype-katex
transforms math blocks into html elements with classes for styling.
Install those two packages via npm:
|
|
|
|
Then we need config gatsby-plugin-mdx
to work with remark-math
and rehype-katex
. My gatsby-config.js
file look like this in then end. gatsby-remark-images
part can be omitted.
|
|
References:
https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-mdx