Next.js MDX Dynamic Import
Discover MDX files with Content Collections, but let Next.js compile them
The method used in this sample does not currently work with turborepo.
Installation
- Follow the instructions to configure MDX routes in your Next.js project
- Install Content Collections: Next.js Quick Start
Configuration
Configure Content Collections that it discover the MDX files, but we exclude the content from the generated files e.g.:
We have to tell Next.js to remove the frontmatter from the MDX files during the compilation because the frontmatter is handled by Content Collections. For this, we have to configure the remark plugins remarkFrontmatter and remarkMdxFrontmatter in the Next.js configuration, e.g.:
Usage
Now we can use the generated allPosts
collections as usual:
But when we want to render the content of a post, we can use a dynamic import to let Next.js compile the MDX file for us: