Published on

Pliny 3단계: Contentlayer 이해와 설정 구성

3단계: Contentlayer 이해와 설정 구성


3-1. Contentlayer란?

Contentlayer는 .mdx 같은 콘텐츠 파일을 정적 타입 정보가 포함된 JavaScript 객체로 변환하는 도구야.

  • .mdxallBlogs[]와 같은 타입 안전 객체로 변환
  • Next.js에서 getStaticProps 없이도 정적 콘텐츠를 바로 사용 가능
  • 타입스크립트와 강력하게 결합됨

3-2. Pliny의 설정 파일 위치

contentlayer.config.ts

3-3. 주요 구조: defineDocumentType

import { defineDocumentType, makeSource } from "contentlayer/source-files";

export const Blog = defineDocumentType(() => ({
  name: "Blog",
  filePathPattern: `blog/*.mdx`,
  contentType: "mdx",
  fields: {
    title: { type: "string", required: true },
    date: { type: "date", required: true },
    summary: { type: "string", required: true },
    draft: { type: "boolean" },
    tags: { type: "list", of: { type: "string" } },
    images: { type: "list", of: { type: "string" } },
  },
  computedFields: {
    slug: {
      type: "string",
      resolve: (doc) => doc._raw.flattenedPath,
    },
  },
}));

3-4. makeSource 구성

export default makeSource({
  contentDirPath: "content",
  documentTypes: [Blog],
});
  • contentDirPath: 실제 콘텐츠가 위치한 디렉토리
  • documentTypes: 등록된 DocumentType 배열

3-5. 사용 예: 모든 블로그 글 가져오기

import { allBlogs } from "contentlayer/generated";
export async function getStaticProps() {
  return { props: { posts: allBlogs } };
}

이제 타입 보장된 posts 배열을 그대로 컴포넌트에서 사용 가능.


요약

  • Contentlayer는 .mdx를 정적 데이터로 변환 + 타입 보장
  • defineDocumentType()으로 문서 타입 정의
  • computedFields로 slug, URL, ID 등 자동 계산
  • allBlogs, allAuthors 등으로 전체 콘텐츠 접근 가능

심화학습

Q1
Contentlayer에서 computedFields.slug 대신 커스텀 경로를 만들고 싶으면 어떻게 설정해야 할까?

A1
computedFields.slug 항목에서 문자열을 직접 조합하면 된다. 예를 들어 언어/타입 기반 경로를 만들고 싶다면:

slug: {
  type: "string",
  resolve: (doc) => `${doc.lang}/${doc._raw.flattenedPath}`,
}

Q2
다양한 콘텐츠 타입(blog 외에 docs, projects 등)을 동시에 쓰려면 어떻게 분리 구성하면 좋을까?

A2
defineDocumentType()을 여러 개 정의하고 makeSource에 배열로 등록하면 된다. 예시:

export const Blog = defineDocumentType(...);
export const Project = defineDocumentType(...);

export default makeSource({
  contentDirPath: "content",
  documentTypes: [Blog, Project],
});

content/blog, content/projects로 폴더도 분리하여 관리할 수 있다.


Q3
빌드시 Contentlayer 에러가 발생한다면 어떤 순서로 설정 파일을 점검해야 할까?

A3

  1. required: true인 필드가 누락된 파일이 있는지 확인
  2. computedFields에서 외부 참조 변수(doc 등)가 잘못된 위치에 있는지 확인
  3. 파일 경로 패턴(filePathPattern)이 실제 구조와 맞는지 확인
  4. MDX 문법 오류나 JSX 컴포넌트가 제대로 닫혔는지도 체크