コンテンツへスキップ
Fumadocs

Content Collections

Fumadocs で Content Collections を使用する

Content Collections は、コンテンツを型安全なデータコレクションに変換するライブラリです。

セットアップ

Content Collections の公式ガイドに従って、お使いの React フレームワークに Content Collections をセットアップしてください。

MDX が設定されていることを確認してください。

npm i @content-collections/mdx

Fumadocs と統合するには、content-collections.ts に以下を追加します。

content-collections.ts
import { defineCollection, defineConfig } from '@content-collections/core';
import { transformMDX } from '@fumadocs/content-collections/configuration';
import { metaSchema, pageSchema } from 'fumadocs-core/source/schema';

const docs = defineCollection({
  name: 'docs',
  directory: 'content/docs',
  include: '**/*.mdx',
  schema: pageSchema,
  transform: transformMDX,
});

const metas = defineCollection({
  name: 'meta',
  directory: 'content/docs',
  include: '**/meta.json',
  parser: 'json',
  schema: metaSchema,
});

export default defineConfig({
  collections: [docs, metas],
});

次に、これを loader() に渡します。

lib/source.ts
import { allDocs, allMetas } from 'content-collections';
import { loader } from 'fumadocs-core/source';
import { createMDXSource } from '@fumadocs/content-collections';

export const source = loader({
  baseUrl: '/docs',
  source: createMDXSource(allDocs, allMetas),
});

これで完了です。Source API から、ページや生成されたページツリーにアクセスできます。

import { getPage } from '@/lib/source';

const page = getPage(slugs);

// MDX の出力
page?.data.body;

// 目次
page?.data.toc;

// 構造化データ(Search API 用)
page?.data.structuredData;

MDX オプション

MDX のオプションは transformMDX 関数でカスタマイズできます。

import { defineCollection } from '@content-collections/core';
import { transformMDX } from '@fumadocs/content-collections/configuration';

const docs = defineCollection({
  transform: (document, context) =>
    transformMDX(document, context, {
      // ここにオプションを指定
    }),
});

コンポーネントのインポート

Fumadocs UI など、他のパッケージのコンポーネントを使用するには、<MDXContent /> コンポーネントに渡してください。

import { MDXContent } from '@content-collections/mdx/react';
import { getMDXComponents } from '@/components/mdx';

return <MDXContent code={page.data.body} components={getMDXComponents()} />;

MDXファイル内でインポートすることもできますが、推奨されません。

詳細解説: なぜ推奨されないのか?

Content Collectionsは、MDXファイルのバンドルにmdx-bundlerを使用しています。

node modulesからパッケージをインポートできるように、FumadocsはMDX Bundlerのcwdオプションにデフォルト値を設定しています。 これで問題なく動作しますが、それでもMDXファイル内でコンポーネントをインポートすることは推奨しません。

理由:

  • コンポーネントをesbuildでバンドルする必要がありますが、本来これはフレームワークのバンドラー(ViteやTurbopackなど)が担うべき処理です。
  • MDXファイルを変更せずに、コンポーネントのインポートパスをリファクタリングできます。
  • Remote Sourcesを使用する場合、MDXファイルにインポートを記述する意味がありません。

How is this guide?

最終更新日