内容集合
为 Fumadocs 使用内容集合
内容集合 是一个将你的内容转换为类型安全数据集合的库。
安装
🌐 Setup
按照他们的官方指南为你的 React 框架设置内容集合。
🌐 Follow their official guide to setup Content Collections for your React framework.
确保你已配置 MDX:
🌐 Make sure you have MDX configured:
npm i @content-collections/mdx要与 Fumadocs 集成,请将以下内容添加到你的 content-collections.ts 中。
🌐 To integrate with Fumadocs, add the following to your content-collections.ts.
import { defineCollection, defineConfig } from '@content-collections/core';
import {
frontmatterSchema,
metaSchema,
transformMDX,
} from '@fumadocs/content-collections/configuration';
const docs = defineCollection({
name: 'docs',
directory: 'content/docs',
include: '**/*.mdx',
schema: frontmatterSchema,
transform: transformMDX,
});
const metas = defineCollection({
name: 'meta',
directory: 'content/docs',
include: '**/meta.json',
parser: 'json',
schema: metaSchema,
});
export default defineConfig({
collections: [docs, metas],
});然后把它交给 loader()。
🌐 And pass it to loader().
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 访问页面和生成的页面树。
🌐 Done! You can access the pages and generated page tree from Source API.
import { getPage } from '@/lib/source';
const page = getPage(slugs);
// MDX output
page?.data.body;
// Table of contents
page?.data.toc;
// Structured Data, for Search API
page?.data.structuredData;MDX 选项
🌐 MDX Options
你可以在 transformMDX 函数中自定义 MDX 选项。
🌐 You can customise MDX options in the transformMDX function.
import { defineCollection } from '@content-collections/core';
import { transformMDX } from '@fumadocs/content-collections/configuration';
const docs = defineCollection({
transform: (document, context) =>
transformMDX(document, context, {
// options here
}),
});导入组件
🌐 Import Components
要使用来自其他包(如 Fumadocs UI)的组件,请将它们传递给你的 <MDXContent /> 组件。
🌐 To use components from other packages like Fumadocs UI, pass them to your <MDXContent /> component.
import { MDXContent } from '@content-collections/mdx/react';
import { getMDXComponents } from '@/mdx-components';
return <MDXContent code={page.data.body} components={getMDXComponents()} />;你也可以在 MDX 文件中导入它们,但不推荐这样做。
🌐 You can also import them in MDX Files, but it is not recommended.
深度探讨:为什么?
内容集合使用 mdx-bundler 来打包 MDX 文件。
为了支持从 node 模块导入包,Fumadocs 在 MDX Bundler 的 cwd 选项中添加了默认值。
它运行良好,但我们仍然不建议在 MDX 文件中导入组件。
原因:
- 它需要 esbuild 来打包这些组件,而这本应由框架的打包工具(例如 Vite 或 Turbopack)来完成
- 你可以在不更改 MDX 文件的情况下重构组件的导入路径。
- 对于远程资源,在 MDX 文件中添加导入没有意义。
Last updated on
