Minimum working setup to use MDX file within Next.js.
npm install @next/mdx @mdx-js/loader @mdx-js/react --save-dev
next.config.mjs
// next.config.mjs is at the same directory location as the package.json file.
import createMDX from '@next/mdx';
const nextConfig = {}
// Configure pageExtensions to also include *.mdx
nextConfig.pageExtensions = ['jsx', 'mdx', 'ts', 'tsx'];
const withMDX = createMDX({
// Add markdown plugins here, as desired
})
export default withMDX(nextConfig)
{/*
./page/hello.mdx
Remember: mdx is in fact an jsx file that allow markdown syntax.
Markdown autolinks(e.g. <https://openwritings.net>) is not supported: https://github.com/mdx-js/mdx/issues/1049
*/}
export const name = "Joe";
#### Welcome
My name is {name}.
Change style for each HTML elements in mdx-components.js
(It has to be .js
).
Place it in the same directory where package.json reside.
// mdx-components.js
import Image from 'next/image'
// This file allows you to provide custom React components
// to be used in MDX files. You can import and use any
// React component you want, including inline styles,
// components from other libraries, and more.
export function useMDXComponents(components) {
return {
// Allows customizing built-in components, e.g. to add styling.
h1: ({ children }) => (<h1 style={{ color: 'red', fontSize: '50px' }}>{children}</h1>),
h2: ({ children }) => (<h2 style={{ color: 'blue', fontSize: '40px' }}>{children}</h2>),
h3: ({ children }) => (<h3 style={{ color: 'green', fontSize: '30px' }}>{children}</h3>),
img: (props) => (
<Image
sizes="100vw"
style={{ width: '100%', height: 'auto' }}
{...props}
/>
),
...components,
}
}