Introduction#
GitHub this note show how to setup MDX in Next.js App Router
Project Structure#
|--app|--blog|--layout.tsx|--page.mdx|--global.css|--layout.tsx|--pages.tsx|--next.config.js|--package.json|--tailwind.config.js|--mdx-components.tsx
MDX Component#
Let create a mdx-components.tsx file at the root of the project directory. This will
- Convert mdx to react component (wrapper)
- We can customise styles
import type { MDXComponents } from 'mdx/types'export function useMDXComponents(components: MDXComponents): MDXComponents {return {// Allows customizing built-in components, e.g. to add styling.h2: ({ children }) => <h2 style={{ fontSize: '2rem' }}>{children}</h2>,img: ({ children }) => <div style={{ width: '200px' }}>{children}</div>,...components}}
Next Config#
/** @type {import('next').NextConfig} */const nextConfig = {pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'mdx'],experimental: {appDir: true,mdxRs: true}}const withMDX = require('@next/mdx')({options: {remarkPlugins: [],rehypePlugins: []// If you use `MDXProvider`, uncomment the following line.// providerImportSource: "@mdx-js/react",}})module.exports = withMDX(nextConfig)
Tailwind Typography#
export default function BlogLayout({children // will be a page or nested layout}: {children: React.ReactNode}) {return <div className="prose font-mplus text-blue-500">{children}</div>}
Setup font in Tailwind
module.exports = {darkMode: 'class',content: ['./pages/**/*.{js,ts,jsx,tsx,mdx}','./components/**/*.{js,ts,jsx,tsx,mdx}','./app/**/*.{js,ts,jsx,tsx,mdx}'],theme: {extend: {typography: {DEFAULT: {css: {maxWidth: 'none'}}},fontFamily: {mplus: ["'M PLUS Rounded 1c'", 'Verdana', 'sans-serif']}}},plugins: [require('@tailwindcss/typography')]}
Add the mplus font into global.css
@import url('https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c:wght@300;500;700&display=swap');@tailwind base;@tailwind components;@tailwind utilities;