FRANCKE.dev

Vite React - MDX Syntax Highlighting

2024-03-08

Vite React - MDX Syntax Highlighting

MDX Syntax Highlighting in Vite React

I'm making this guide, since I wasn't able to find a fitting guide for my project.

Highlight.js

I found the best solution for my need, was to simply use highlight.js. It works by intercepting the pre and code tags created by MDX, and inserting the correct css - in my case using tailwindcss

Before beginning

Terminal


yarn add highlight.js tailwind-highlightjs

Tailwind config

Your Tailwind config should look something like this -->

tailwind.config.mjs

/** @type {import('tailwindcss').Config} */
import 'tailwind-highlightjs'
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    hljs: {
      theme: 'night-owl',
    },
    extend: {},
  },
  plugins: ['tailwind-highlightjs'],
  safelist: [
    {
      pattern: /hljs+/,
    },
  ],
}

Turn on the lights

To activate highlight.js you have to go to the component, that displays your MDX file. In my case it's called Post. Here we will add the hljs.hightlightAll() This function will find and intercept all the "codeblock". It's important to contain the function call inside a useEffect, so it only runs once.

Post.tsx

import hljs from "highlight.js";
import 'highlight.js/styles/night-owl.css';
import {useEffect} from "react";


export function Post({ children }: { children?: React.ReactNode }) {
    useEffect(() => {
        hljs.highlightAll()
    }, []);
    return (
        <div className="w-full min-h-48 text-white flex justify-center self-center pt-8 pb-8">
            <div className="text-lg w-[90vw] bg-gray-950 p-8 rounded-2xl min-h-80 pl-9 pr-8">
                {children}
            </div>
        </div>
    )
}

Then add this to your MDX component definition components={{'code': (props) => (<code {...props}/>)}}

Styling

As you may have noticed, I've picked a different theme in my tailwind config. Highlight.js comes with a pretty large catalog of themes. You can see the list here: Highlight.js examples