📦 plugin-content-docs
Provides the Docs functionality and is the default docs plugin for Docusaurus.
安装流程
- npm
- Yarn
- pnpm
npm install --save @docusaurus/plugin-content-docs
yarn add @docusaurus/plugin-content-docs
pnpm add @docusaurus/plugin-content-docs
提示
如果你已经安装了 @docusaurus/preset-classic,就不需要安装这个包了。
你可以通过预设选项来配置这个插件。
配置
接受的字段:
| 参数 | 类型 | 默认值 | 描述 | 
|---|---|---|---|
| path | string | 'docs' | 文档内容目录的文件系统路径,相对于站点目录。 | 
| editUrl | string | EditUrlFunction | undefined | 编辑文档的基础 URL。 最终的 URL 会按照 editUrl + relativeDocPath计算。 使用函数可以允许你更精细地控制每一个文件。 完全忽略这个变量就会禁用编辑链接。 | 
| editLocalizedFiles | boolean | false | 编辑 URL 会指向本地化的文件,而不是原始的未翻译文件。 如果 editUrl是一个函数,会完全忽略此选项。 | 
| editCurrentVersion | boolean | false | 编辑 URL 会永远指向当前版本文档而不是历史版本。 如果 editUrl是一个函数,会完全忽略此选项。 | 
| routeBasePath | string | 'docs' | 站点文档部分的 URL 前缀。 不要包含末尾斜杠。 如果要部署没有基础路径的文档,请使用 /。 | 
| tagsBasePath | string | 'tags' | 站点标签列表部分的 URL 前缀。 会被添加到 routeBasePath后面。 | 
| include | string[] | ['**/*.{md,mdx}'] | 相对于内容路径的 glob 模式列表,匹配到的 Markdown 文件会被构建。 | 
| exclude | string[] | 见示例配置 | Glob 模式列表,匹配到的 Markdown 文件会被排除。 在 include选项的基础上进一步细调。 | 
| sidebarPath | false | string | undefined | 侧边栏配置的路径。 false会禁用侧边栏,undefined会创建一个完全自动生成的侧边栏。 | 
| sidebarCollapsible | boolean | true | 侧边栏类别是否默认可折叠。 另见可折叠类别 | 
| sidebarCollapsed | boolean | true | 侧边栏类别是否默认被折叠。 另见默认展开分类 | 
| sidebarItemsGenerator | SidebarGenerator | 略 | 用于将 'autogenerated'类型的侧边栏项目替换为真正的侧边栏项(文档、类别、链接……)的函数。 另见自定义侧边栏项生成器 | 
| numberPrefixParser | boolean |PrefixParser | 略 | 自定义从文件名中提取数字前缀的逻辑。 false会禁用这种行为并保持文件名不变,true会使用默认的解析器。 另见使用数字前缀 | 
| docLayoutComponent | string | '@theme/DocPage' | 每个文档页面的根布局组件。 提供了版本的数据 context,不会在切换文档时卸载。 | 
| docItemComponent | string | '@theme/DocItem' | 文档主容器,包括了目录、页面导航等。 | 
| docTagsListComponent | string | '@theme/DocTagsListPage' | 标签列表页的根组件 | 
| docTagDocListComponent | string | '@theme/DocTagDocListPage' | 「包含某标签的所有文档」页面的根组件。 | 
| docCategoryGeneratedIndexComponent | string | '@theme/DocCategoryGeneratedIndexPage' | 自动生成类别索引页的根组件。 | 
| remarkPlugins | any[] | [] | 传递给 MDX 的 Remark 插件。 | 
| rehypePlugins | any[] | [] | 传递给 MDX 的 Rehype 插件。 | 
| beforeDefaultRemarkPlugins | any[] | [] | 在 Docusaurus 默认 Remark 插件之前传递给 MDX 的自定义 Remark 插件。 | 
| beforeDefaultRehypePlugins | any[] | [] | 在 Docusaurus 默认 Rehype 插件之前传递给 MDX 的自定义 Rehype 插件。 | 
| showLastUpdateAuthor | boolean | false | 是否显示最后更新文档的作者。 | 
| showLastUpdateTime | boolean | false | 是否显示最后更新文档的时间。 | 
| breadcrumbs | boolean | true | 在文档页面上启用或禁用面包屑导航。 | 
| disableVersioning | boolean | false | 即使存在多个版本,也明确禁用分版功能。 这会让网站只包含当前版本。  如果 includeCurrentVersion: false并且disableVersioning: true,会报错。 | 
| includeCurrentVersion | boolean | true | 包含文档的当前版本。 | 
| lastVersion | string | versions.json中的第一个版本 | 文档类的导航栏项会默认显示并跳转到的文档版本。 | 
| onlyIncludeVersions | string[] | 所有版本 | 只包含所有可用版本中的一个子集。 | 
| versions | VersionsConfig | {} | 独立自定义每个版本的属性。 | 
类型
EditUrlFunction
type EditUrlFunction = (params: {
  version: string;
  versionDocsDirPath: string;
  docPath: string;
  permalink: string;
  locale: string;
}) => string | undefined;
PrefixParser
type PrefixParser = (filename: string) => {
  filename: string;
  numberPrefix?: number;
};
SidebarGenerator
type SidebarGenerator = (generatorArgs: {
  /** 需要转换的 "autogenerated" 类型侧边栏项 */
  item: {type: 'autogenerated'; dirName: string};
  /** 这个侧边栏所属的版本的一些有用元数据。 */
  version: {contentPath: string; versionName: string};
  /** 此版本的所有文档(未经筛选)。 */
  docs: {
    id: string;
    title: string;
    frontMatter: DocFrontMatter & Record<string, unknown>;
    source: string;
    sourceDirName: string;
    sidebarPosition?: number | undefined;
  }[];
  /** 此插件配置的数字前缀解析器。 */
  numberPrefixParser: PrefixParser;
  /** 你可以覆盖的默认类别索引匹配器。 */
  isCategoryIndex: CategoryIndexMatcher;
  /**
   * 每个键是相对于文档内容目录的路径,值是类别元数据文件的内容。
   */
  categoriesMetadata: {[filePath: string]: CategoryMetadata};
  /**
   * 可以用来复用/增强 Docusaurus 默认的侧边栏生成逻辑。
   */
  defaultSidebarItemsGenerator: SidebarGenerator;
  // 返回一个侧边栏项的数组——和你在 sidebars.js 中可以声明的一致,
  // 只是不包括简写。 See https://docusaurus.io/docs/sidebar/items
}) => Promise<SidebarItem[]>;
type CategoryIndexMatcher = (param: {
  /** 文件名,不包括扩展名 */
  fileName: string;
  /**
   * 目录名列表,从最低到最高层。
   * 如果没有目录名,值为 ['.']
   */
  directories: string[];
  /** 扩展名,包含开头的点 */
  extension: string;
}) => boolean;
VersionsConfig
type VersionConfig = {
  /**
   * The base path of the version, will be appended to `baseUrl` +
   * `routeBasePath`.
   */
  path?: string;
  /** The label of the version to be used in badges, dropdowns, etc. */
  label?: string;
  /** The banner to show at the top of a doc of that version. */
  banner?: 'none' | 'unreleased' | 'unmaintained';
  /** Show a badge with the version label at the top of each doc. */
  badge?: boolean;
  /** Prevents search engines from indexing this version */
  noIndex?: boolean;
  /** Add a custom class name to the <html> element of each doc */
  className?: string;
};
type VersionsConfig = {[versionName: string]: VersionConfig};
示例配置
你可以通过预设选项或插件选项来配置这个插件。
提示
大多数 Docusaurus 用户通过预设选项配置此插件。
- Preset options
- Plugin options
If you use a preset, configure this plugin through the preset options:
docusaurus.config.js
module.exports = {
  presets: [
    [
      '@docusaurus/preset-classic',
      {
        docs: {
          path: 'docs',
          breadcrumbs: true,
          // 一般使用场景:字符串 editUrl
          // editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/',
          // 高级使用场景:函数 editUrl
          editUrl: ({versionDocsDirPath, docPath}) =>
            `https://github.com/facebook/docusaurus/edit/main/website/${versionDocsDirPath}/${docPath}`,
          editLocalizedFiles: false,
          editCurrentVersion: false,
          routeBasePath: 'docs',
          include: ['**/*.md', '**/*.mdx'],
          exclude: [
            '**/_*.{js,jsx,ts,tsx,md,mdx}',
            '**/_*/**',
            '**/*.test.{js,jsx,ts,tsx}',
            '**/__tests__/**',
          ],
          sidebarPath: 'sidebars.js',
          async sidebarItemsGenerator({
            defaultSidebarItemsGenerator,
            numberPrefixParser,
            item,
            version,
            docs,
            isCategoryIndex,
          }) {
            // 使用提供的数据生成一个自定义侧边栏切片
            return [
              {type: 'doc', id: 'intro'},
              {
                type: 'category',
                label: 'Tutorials',
                items: [
                  {type: 'doc', id: 'tutorial1'},
                  {type: 'doc', id: 'tutorial2'},
                ],
              },
            ];
          },
          numberPrefixParser(filename) {
            // 实现你自己的数字前缀提取逻辑
            const numberPrefix = findNumberPrefix(filename);
            // 匹配到前缀:返回前缀和处理好的文件名
            if (numberPrefix) {
              return {
                numberPrefix,
                filename: filename.replace(prefix, ''),
              };
            }
            // 没有匹配到数字前缀
            return {numberPrefix: undefined, filename};
          },
          docLayoutComponent: '@theme/DocPage',
          docItemComponent: '@theme/DocItem',
          remarkPlugins: [require('remark-math')],
          rehypePlugins: [],
          beforeDefaultRemarkPlugins: [],
          beforeDefaultRehypePlugins: [],
          showLastUpdateAuthor: false,
          showLastUpdateTime: false,
          disableVersioning: false,
          includeCurrentVersion: true,
          lastVersion: undefined,
          versions: {
            current: {
              label: 'Android SDK v2.0.0 (WIP)',
              path: 'android-2.0.0',
              banner: 'none',
            },
            '1.0.0': {
              label: 'Android SDK v1.0.0',
              path: 'android-1.0.0',
              banner: 'unmaintained',
            },
          },
          onlyIncludeVersions: ['current', '1.0.0', '2.0.0'],
        },
      },
    ],
  ],
};
If you are using a standalone plugin, provide options directly to the plugin:
docusaurus.config.js
module.exports = {
  plugins: [
    [
      '@docusaurus/plugin-content-docs',
      {
        path: 'docs',
        breadcrumbs: true,
        // 一般使用场景:字符串 editUrl
        // editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/',
        // 高级使用场景:函数 editUrl
        editUrl: ({versionDocsDirPath, docPath}) =>
          `https://github.com/facebook/docusaurus/edit/main/website/${versionDocsDirPath}/${docPath}`,
        editLocalizedFiles: false,
        editCurrentVersion: false,
        routeBasePath: 'docs',
        include: ['**/*.md', '**/*.mdx'],
        exclude: [
          '**/_*.{js,jsx,ts,tsx,md,mdx}',
          '**/_*/**',
          '**/*.test.{js,jsx,ts,tsx}',
          '**/__tests__/**',
        ],
        sidebarPath: 'sidebars.js',
        async sidebarItemsGenerator({
          defaultSidebarItemsGenerator,
          numberPrefixParser,
          item,
          version,
          docs,
          isCategoryIndex,
        }) {
          // 使用提供的数据生成一个自定义侧边栏切片
          return [
            {type: 'doc', id: 'intro'},
            {
              type: 'category',
              label: 'Tutorials',
              items: [
                {type: 'doc', id: 'tutorial1'},
                {type: 'doc', id: 'tutorial2'},
              ],
            },
          ];
        },
        numberPrefixParser(filename) {
          // 实现你自己的数字前缀提取逻辑
          const numberPrefix = findNumberPrefix(filename);
          // 匹配到前缀:返回前缀和处理好的文件名
          if (numberPrefix) {
            return {
              numberPrefix,
              filename: filename.replace(prefix, ''),
            };
          }
          // 没有匹配到数字前缀
          return {numberPrefix: undefined, filename};
        },
        docLayoutComponent: '@theme/DocPage',
        docItemComponent: '@theme/DocItem',
        remarkPlugins: [require('remark-math')],
        rehypePlugins: [],
        beforeDefaultRemarkPlugins: [],
        beforeDefaultRehypePlugins: [],
        showLastUpdateAuthor: false,
        showLastUpdateTime: false,
        disableVersioning: false,
        includeCurrentVersion: true,
        lastVersion: undefined,
        versions: {
          current: {
            label: 'Android SDK v2.0.0 (WIP)',
            path: 'android-2.0.0',
            banner: 'none',
          },
          '1.0.0': {
            label: 'Android SDK v1.0.0',
            path: 'android-1.0.0',
            banner: 'unmaintained',
          },
        },
        onlyIncludeVersions: ['current', '1.0.0', '2.0.0'],
      },
    ],
  ],
};
Markdown 前言
Markdown 文档可以使用以下前言元数据字段。前言的两端应用 --- 包裹。
接受的字段:
| 参数 | 类型 | 默认值 | 描述 | 
|---|---|---|---|
| id | string | 文件路径(包括文件夹,不含扩展名) | 文档的唯一 ID。 | 
| title | string | Markdown 标题或 id | 你的文档使用的文本标题。 用于页面元数据和多个地方的备用值(侧边栏、下篇/上篇按钮……)。 如果 Markdown 内容没有标题,它会被自动添加到你的文档顶部。 | 
| pagination_label | string | sidebar_label或title | 这篇文档在上一篇/下一篇按钮中显示的文本 | 
| sidebar_label | string | title | 这篇文档在侧边栏中显示的文本 | 
| sidebar_position | number | 默认排序 | 使用 autogenerated自动生成侧边栏项目时,控制文档在侧边栏中出现的位置顺序。 另见自动生成侧边栏。 | 
| sidebar_class_name | string | undefined | 在使用自动生成侧边栏时,给相应的侧边栏标签一个特殊类名。 | 
| sidebar_custom_props | object | undefined | Assign custom props to the sidebar item referencing this doc | 
| displayed_sidebar | string | undefined | Force the display of a given sidebar when browsing the current document. Read the multiple sidebars guide for details. | 
| hide_title | boolean | false | 是否隐藏文档顶部显示的标题。 此选项只会隐藏前言中定义的标题,对于 Markdown 文档顶部的标题没有任何影响。 | 
| hide_table_of_contents | boolean | false | 是否隐藏右侧的文档目录。 | 
| toc_min_heading_level | number | 2 | 目录中显示的最小标题层级。 必须介于 2 到 6 之间,并且小于等于最大值。 | 
| toc_max_heading_level | number | 3 | 目录中显示的最大标题层级。 必须介于 2 和 6。 | 
| pagination_next | string | null | 侧边栏的下一个文档 | 「下篇文档」按钮链接到的文档 ID。 null会禁用本页的「下篇文档」按钮。 | 
| pagination_prev | string | null | 侧边栏的上一个文档 | 「上篇文档」按钮链接到的文档 ID。 null会禁用本页的「上篇文档」按钮。 | 
| parse_number_prefixes | boolean | numberPrefixParser插件选项 | 是否禁用本文档的数字前缀解析。 另见使用数字前缀. | 
| custom_edit_url | string | 使用 editUrl插件选项计算 | 编辑此文档时要跳转到的 URL。 | 
| keywords | string[] | undefined | 用于搜索引擎优化的文档关键词元标签。 | 
| description | string | Markdown 正文的第一行 | 文档的描述信息,会生成 <head>中被搜索引擎读取的<meta name="description" content="..."/>和<meta property="og:description" content="..."/>。 | 
| image | string | undefined | 显示文档链接时所用的缩略图或封面。 | 
| slug | string | 文件路径 | 自定义文档的 URL ( /<routeBasePath>/<slug>)。 支持多种形式:slug: my-doc、slug: /my/path/myDoc、slug: /。 | 
| tags | Tag[] | undefined | 一个列表,由字符串或者包含 label和permalink字符串字段的对象构成,用于提供文档标签。 | 
| draft | boolean | false | 一个布尔值,表明文档处于未完成状态。 文档草稿只会在开发模式下显示。 | 
| last_update | FileChange | undefined | 允许覆盖最后更新的作者、日期。 日期可以是任意可解析的日期字符串。 | 
type Tag = string | {label: string; permalink: string};
type FileChange = {date: string; author: string};
示例:
---
id: doc-markdown
title: 文档 Markdown 特性
hide_title: false
hide_table_of_contents: false
sidebar_label: Markdown
sidebar_position: 3
pagination_label: Markdown 特性
custom_edit_url: https://github.com/facebook/docusaurus/edit/main/docs/api-doc-markdown.md
description: 我解决不了这个问题时在哪里找到你
keywords:
  - docs
  - docusaurus
image: https://i.imgur.com/mErPwqL.png
slug: /myDoc
last_update:
  date: 1/1/2000
  author: 自定义作者名
---
# Markdown 特性
我的 Markdown 文档的内容
i18n
Read the i18n introduction first.
翻译文件位置
- 基础路径:website/i18n/[语言]/docusaurus-plugin-content-docs
- 多实例路径:website/i18n/[语言]/docusaurus-plugin-content-docs-[插件 ID]
- JSON files: extracted with docusaurus write-translations
- Markdown 文件:website/i18n/[语言]/docusaurus-plugin-content-docs/[版本名]
文件系统结构示例
website/i18n/[语言]/docusaurus-plugin-content-docs
│
│ # website/docs 的翻译
├── current
│   ├── api
│   │   └── config.md
│   └── getting-started.md
├── current.json
│
│ # website/versioned_docs/version-1.0.0 的翻译
├── version-1.0.0
│   ├── api
│   │   └── config.md
│   └── getting-started.md
└── version-1.0.0.json