My Work Notes

30 Aug 2023

Integrating MDX with Vite and React

MDX is a format that lets you write JSX in your Markdown documents (did you get it? It’s like MD + JSX 😱). Here are the steps to use it with Vite and React.

  1. Install dependencies:
npm install @mdx-js/react @mdx-js/rollup
  1. Add @mdx-js/rollup to vite.config.js:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig(async () => {
  const mdx = await import('@mdx-js/rollup');

  return {
    plugins: [react(), mdx()],
  }
});

We can’t use import at the top level because vite.config.js is CommonJS, not ESM, and @mdx-js/rollup is ESM only.

Actually, that’s it. You can now import .mdx files in your project. Below is a basic example of how to use React components inside MDX.

  1. Write some MDX (chill out, it’s just Markdown):
# Hello, world

This is a simple hello world example.

<em>This text style is italicized</em>

Here <em> is a JSX component, which we will pass to the MDX provider.

  1. Import MDXProvider from @mdx-js/react and pass components to it:
import React from 'react';
import {MDXProvider} from '@mdx-js/react';
import MyMarkdown from './MyMarkdown.mdx';

const components = {
  em: props => <i {...props} />
}

const MyPage = () => (
  <MDXProvider components={components}>
    <MyMarkdown />
  </MDXProvider>
);

export default MyPage;

Alternatively, you can pass components directly to the MDX component:

const MyPage = () => (
-  <MDXProvider components={components}>
-    <Quickstart />
-   </MDXProvider>
+  <Quickstart components={components} />
);
  1. Now we can see the result: result in browser

There’s a lot more to MDX, but this is a good starting point. You can find more information in the official documentation.