Notes

Syntax highlighting for fenced code blocks in Gatsby MDX

Edit on GitHub

Gatsby
2 minutes

My Gatsby setup uses MDX. And i need to add syntax highlighting to the fenced code blocks

Had to install the prism-react-renderer plugin

1npm install --save prism-react-renderer

And in my gatsby-browser.js i needed to add the following code

 1import React from 'react'
 2import { MDXProvider } from '@mdx-js/react'
 3import Highlight, { defaultProps, theme } from 'prism-react-renderer'
 4import github from 'prism-react-renderer/themes/github'
 5
 6/* eslint-disable */
 7const component = {
 8  pre: (props) => {
 9    const className = props.children.props.className || ''
10    const matches = className.match(/language-(?<lang>.*)/)
11    return (
12      <Highlight
13        {...defaultProps}
14        code={props.children.props.children}
15        language={matches && matches.groups && matches.groups.lang ? matches.groups.lang : ''}
16        theme={github}
17      >
18        {({ className, style, tokens, getLineProps, getTokenProps }) => (
19          <pre className={className} style={style}>
20            {tokens.map((line, i) => (
21              <div {...getLineProps({ line, key: i })}>
22                {line.map((token, key) => (
23                  <span {...getTokenProps({ token, key })} />
24                ))}
25              </div>
26            ))}
27          </pre>
28        )}
29      </Highlight>
30    )
31  },
32}
33export const wrapRootElement = ({ element }) => {
34  return <MDXProvider components={component}>{element}</MDXProvider>
35}

And that’s it. Now all fenced code blocks in Markdown will show proper syntax highlighting

The theme i am using came with the plugin, but i plan on creating my custom theme to match the site.

Will probably have to add support for additional languages

Add support for additional languages

You have to install the prismjs package

1npm i prismjs

And then add the following to gatsby-browser.js

1import Prism from 'prism-react-renderer/prism'
2;(typeof global !== 'undefined' ? global : window).Prism = Prism // gotta do this one otherwise it'll say Prism is not defined
3
4require('prismjs/components/prism-csharp')

You can see a list of included languages here and all supported langs here