Fumadocs

Next.js

在 Next.js 中使用 Fumadocs MDX

设置

为您的 Next.js 应用程序设置 Fumadocs MDX。

npm i fumadocs-mdx @types/mdx

创建配置文件:

source.config.ts
import { defineDocs, defineConfig } from 'fumadocs-mdx/config';

export const docs = defineDocs({
  dir: 'content/docs',
});

export default defineConfig();

将插件添加到 Next.js 配置中:

next.config.mjs
import { createMDX } from 'fumadocs-mdx/next';

const withMDX = createMDX({
  // customise the config file path
  // configPath: "source.config.ts"
});

/** @type {import('next').NextConfig} */
const config = {
  reactStrictMode: true,
};

export default withMDX(config);

仅支持 ESM

Next.js 配置必须是 .mjs 文件,因为 Fumadocs 仅支持 ESM。

与 Fumadocs 集成

您可以创建一个 lib/source.ts 文件,并从 docs 集合输出中获取 Fumadocs 源。

lib/source.ts
import { docs } from '@/.source';
import { loader } from 'fumadocs-core/source';

export const source = loader({
  baseUrl: '/docs',
  source: docs.toFumadocsSource(),
});

当您运行 next devnext build 时,.source 将被生成。

请确保导入 .source 而非 source.config.ts

与 CI 集成(可选)

您可以运行 fumadocs-mdx 来生成 .source 文件夹。

可选地,您可以在 post install 中运行它,以确保在初始化项目时生成类型。

package.json
{
  "scripts": {
    "postinstall": "fumadocs-mdx"
  }
}

完成

玩得开心!

示例

访问内容

通常,您将通过 loader() 与集合交互,对于多个 docs 集合也是如此。

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

const page = source.getPage(['slugs']);

if (page) {
  // access page data
  console.log(page.data);

  // frontmatter properties are also inside
  console.log(page.data.title);
}

要渲染页面,请将 page.data.body 用作组件。

import { getMDXComponents } from '@/mdx-components';

const MDX = page.data.body;

// set your MDX components with `components` prop
return <MDX components={getMDXComponents()} />;

不使用 loader() 的情况下,您也可以使用集合名称导入 .source 文件夹:

import { defineDocs } from 'fumadocs-mdx/config';

export const docs = defineDocs({
  dir: 'content/docs',
  docs: {
    // options for `doc` collection
  },
  meta: {
    // options for `meta` collection
  },
});

How is this guide?

Last updated on