본문 바로가기

Next.js

Next.js 12-5 Configuring MDX

  Markdown은 텍스트 형식을 지정하는 데 사용되는 경량 마크업 언어이다. 일반 텍스트 구문을 사용하여 작성하고 구조적으로 유효한 HTML로 변환할 수 있다. 일반적으로 웹 사이트 및 블로그에 콘텐츠를 작성하는 데 사용된다.

// input
I **love** using .[Next.js[_(https://nextjs.org/).

// output
<p>I <strong>love</strong> using <a href="https://nextjs.org/">Next.js</a></p>

 

  MDX는 마크다운 파일에서 직접 JSX를 작성할 수 있는 마크다운의 상위 집합이다. 이는 동적 상호 작용을 추가하고 콘텐츠 내에 React 컴포넌트를 포함하는 강력한 방법이다.

  Next.js는 애플리케이션 배부의 로컬 MDX 콘텐츠와 서버에서 동적으로 가져온 원격 MDX 파일을 모두 지원할 수 있다. Next.js 플러그인은 서버 컴포넌트(app의 기본값)에서의 사용 지원을 포함하여 Markdown 및 React 컴포넌트를 HTML로 변환하는 작업을 처리한다.

 

  • @next/mdx

  @next/mdx 패키지는 프로젝트 루트의 next.config.js 파일에서 구성된다. 로컬 파일에서 데이터를 가져오므로 /pages 또는 /app 디렉토리에서 직접 .mdx 확장자를 가진 페이지를 만들 수 있다.

시작하기

  @next/mdx 패키지를 설치한다.

npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdx

  애플리케이션의 루트(app의 상위 폴더)에 mdx-components.tsx를 만든다.

// mdx-components.tsx

import type { MDXComponents } from 'mdx/types'

// 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 components from
// other libraries.

// This file is required to use MDX in `app` directory.
export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    // Allows customizing built-in components, e.g. to add styling.
    // h1: ({ children }) => <h1 style={{ fontSize: "100px" }}>{children}</h1>
    ...components,
  }
}

  mdxRs를 사용하도록 next.config.js를 업데이트한다.

// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig =
  experimental: {
    mdxRs: true,
  },
}

const withMDX = require('@next/mdx')()
module.exports = withMDX(nextConfig)

  앱 디렉토리에 MDX 콘텐츠가 포함된 새 파일을 추가한다.

// app.hello.mdx

Hello, Next.js!

You can import and use React components in MDX files.

  콘텐츠를 표시하려면 페이지 내에서 MDX 파일을 가져온다.

// app/page.tsx

import HelloWorld from './hello.mdx

export default function Page() {
  return <HelloWorld />
}

 

  • Remote MDX

  Markdown 또는 MDX 파일이 애플리케이션 내부에 없으면 서버에서 동적으로 가져올 수 있다. 이는 CMS 또는 기타 데이터 소스에서 콘텐츠를 가져오는 데 유용하다.

  MDX 콘텐츠를 가져오기 위한 두 가지 인기 있는 커뮤니티 패키지인 next-mdx-remote와 contentlayer가 있다. 예를 들어 다음 예제에서는 next-mdx-remote를 사용한다. 주의할 점은 MDX는 JavaScript로 컴파일되고 서버에서 실행된다. 신뢰할 수 있는 소스에서만 MDX 콘텐츠를 가져와야 한다. 그렇지 않으면 원격 코드 실행(RCE)이 발생할 수 있다.

// app/page.tsx

import { MDXRemote } from 'next-mdx-remote/src'

export default async function Home() {
  const res = await fetch('https://...')
  const markdown = await res.text()
  return <MDXRemote source={markdown} />
}

 

  • Layouts

  MDX 콘텐츠 주변의 레이아웃을 공유하려면 앱 라우터에서 기본 제공 레이아웃 지원을 사용할 수 있다.

 

  • Remark and Rehype Plugins

  선택적으로 MDX 콘텐츠를 변환하기 위해 remark 및 rehype 플러그인을 제공할 수 있다. 예를 들어, comment-gfm을 사용하여 GitHub Flavored Markdown을 지원할 수 있다.

  remark와 rehype 생태계는 ESM 전용하므로 next.config.js를 구성 파일로 사용해야 한다.

// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    appDir: 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)