In this article, We'll see what mdx and mdx-bundler are and how to use mdx-bundler with Next.js. What are the other alternatives to mdx-bundler, and how is it different?
What is MDX?
MDX is the extension of Markdown that allows us to write React Component inside the markdown file. I assume that everyone knows about Markdown. If not, follow this to get a basic understanding of Markdown.
The most widely used mdx compiler packages are
In this blog, I used mdx-bundler to compile and bundle my code sourced from . MDX-bundler compiles and bundles our code with built-in support to frontmatter, but the next-mdx-remote package only compiles the code. It's just a compiler.
What is MDX-bundler?
MDX-bundler is an asynchronous function to compile and bundle our MDX files with their dependency. MDX-bundler is best suited for the SSR framework with on-demand bundling.
Create a new project. Now we need to install mdx-bundler into our project.
Let's get started by adding a bundler. It's up to you whether you want to bundle the code on build time() or every request(). In this blog, I bundled the code on build time with incremental static regeneration() to revalidate the cache on every new update.
Now, we need to bundle our code. Import the function from the mdx-bundler package, then pass the required options. Check out this to find all the available options. There are two ways to pass source data to the bundle function.
The first way is to use the source property, and the other is to use the file property. In my case, I used the source property to pass the data.
We have the mdx options property, which allows us to add remark/rehype plugins. With the help of this article from , I created a custom plugin to extract metadata from code blocks.
Now pass this function to mdx options. In my case, this is a rehype plugin, so I'll pass it in the rehype options.
Now, we need to use this bundled code on the client side. To do that, import the function from the mdx-bundler package. Use the hook from react to avoid intensive calculation on every render. In our case, we need to re-run the getMdxComponent function on code change. So we need to add the code string as a dependency. This function returns a component that helps us render the bundled code on the browser.
With the help of mdx-bundler, we can now substitute components. For that, we need to pass components as a prop, and we can replace any components from here and add our custom components.
From the above snippet, we can see replacing the existing pre tag with our Custom styled and passing our custom components .
And that's it. We successfully integrated mdx-bundler with Next.js. If you have any questions or comments, let me know on Twitter at or via email at . But until next time, happy coding!