跳到主要内容

📦 plugin-content-docs

提供 文档 功能,是 Docusaurus 的默认文档插件。

安装

npm install --save @docusaurus/plugin-content-docs
提示

如果您使用预设 @docusaurus/preset-classic,则无需将此插件作为依赖项安装。

您可以通过预设选项配置此插件。

配置

接受的字段:

名称类型默认值描述
pathstring'docs'文件系统上文档内容目录的路径,相对于站点目录。
editUrlstring | EditUrlFunctionundefined编辑您站点的基本 URL。最终 URL 由 editUrl + relativeDocPath 计算。使用函数可以对每个文件进行更细粒度的控制。完全省略此变量将禁用编辑链接。
editLocalizedFilesbooleanfalse编辑 URL 将针对本地化文件,而不是原始未本地化的文件。当 editUrl 是函数时被忽略。
editCurrentVersionbooleanfalse编辑 URL 将始终针对当前版本的文档,而不是旧版本。当 editUrl 是函数时被忽略。
routeBasePathstring'docs'站点文档部分的 URL 路由。不要包含尾随斜杠。使用 / 来发布没有基本路径的文档。
tagsBasePathstring'tags'站点标签列表页面的 URL 路由。它会被添加到 routeBasePath 之前。
includestring[]['**/*.{md,mdx}']要构建的 Markdown 文件的 glob 模式数组,相对于内容路径。
excludestring[]参见示例配置要排除的 Markdown 文件的 glob 模式数组。作为 include 选项的细化。
sidebarPathfalse | stringundefined侧边栏配置文件的路径,在 Node.js 上下文中加载。使用 false 禁用侧边栏,或使用 undefined 创建完全自动生成的侧边栏。
sidebarCollapsiblebooleantrue侧边栏类别默认是否可折叠。另请参见可折叠类别
sidebarCollapsedbooleantrue侧边栏类别默认是否折叠。另请参见默认展开类别
sidebarItemsGeneratorSidebarGenerator省略用于将类型为 'autogenerated' 的侧边栏项目替换为真实侧边栏项目(文档、类别、链接等)的函数。另请参见自定义侧边栏项目生成器
numberPrefixParserboolean | PrefixParser省略用于从文件名中提取数字前缀的自定义解析逻辑。使用 false 禁用此行为并保持文档不变,使用 true 使用默认解析器。另请参见使用数字前缀
docsRootComponentstring'@theme/DocsRoot'所有文档插件页面(包括所有版本)的父组件。在文档页面和版本之间导航时保持挂载。
docVersionRootComponentstring'@theme/DocVersionLayout'单个版本的所有文档页面的父组件(带侧边栏的文档页面、标签页面)。在该特定版本的页面之间导航时保持挂载。
docRootComponentstring'@theme/DocRoot'所有带侧边栏的文档页面的父组件(常规文档页面、类别生成的索引页面)。在此类页面之间导航时保持挂载。
docItemComponentstring'@theme/DocItem'主文档容器,包含目录、分页等。
docTagsListComponentstring'@theme/DocTagsListPage'标签列表页面的根组件
docTagDocListComponentstring'@theme/DocTagDocListPage'"包含标签 X 的文档"页面的根组件。
docCategoryGeneratedIndexComponentstring'@theme/DocCategoryGeneratedIndexPage'生成的类别索引页面的根组件。
remarkPluginsany[][]传递给 MDX 的 Remark 插件。
rehypePluginsany[][]传递给 MDX 的 Rehype 插件。
recmaPluginsany[][]传递给 MDX 的 Recma 插件。
beforeDefaultRemarkPluginsany[][]在默认 Docusaurus Remark 插件之前传递给 MDX 的自定义 Remark 插件。
beforeDefaultRehypePluginsany[][]在默认 Docusaurus Rehype 插件之前传递给 MDX 的自定义 Rehype 插件。
showLastUpdateAuthorbooleanfalse是否显示最后更新文档的作者。
showLastUpdateTimebooleanfalse是否显示文档最后更新的日期。这需要在构建期间访问 git 历史记录,因此对于浅克隆(CI 系统的常见默认设置)将无法正确工作。对于 GitHub actions/checkout,请使用 fetch-depth: 0
disableVersioningbooleanfalse即使存在多个版本也明确禁用版本控制。这将使站点仅包含当前版本。如果 includeCurrentVersion: falsedisableVersioning: true,则会出错。
includeCurrentVersionbooleantrue包含文档的当前版本。
lastVersionstringversions.json 中的第一个版本文档导航栏项目优先导航和默认显示的版本。
onlyIncludeVersionsstring[]所有可用版本仅包含所有可用版本的子集。
versionsVersionsConfig{}独立自定义每个版本的属性。
tagsstring | false | null | undefinedtags.yml列出预定义标签的 YAML 文件的路径。相对于文档版本内容目录。
onInlineTags'ignore' | 'log' | 'warn' | 'throw'warn当文档包含内联标签(未出现在预定义标签列表中,通常是 docs/tags.yml)时的插件行为。

类型

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 中声明的相同,除了简写。请参见 https://docusaurus.io/docs/sidebar/items
}) => Promise<SidebarItem[]>;

type CategoryIndexMatcher = (param: {
/** 文件名,不包括扩展名 */
fileName: string;
/**
* 目录列表,从最低级到最高级。
* 如果没有目录名,目录为 ['.']
*/
directories: string[];
/** 扩展名,带前导点 */
extension: string;
}) => boolean;

VersionsConfig

type VersionConfig = {
/**
* 版本的基本路径,将附加到 `baseUrl` +
* `routeBasePath`。
*/
path?: string;
/** 用于徽章、下拉菜单等的版本标签。 */
label?: string;
/** 要在该版本的文档顶部显示的横幅。 */
banner?: 'none' | 'unreleased' | 'unmaintained';
/** 在每个文档顶部显示带有版本标签的徽章。 */
badge?: boolean;
/** 阻止搜索引擎索引此版本 */
noIndex?: boolean;
/** 为每个文档的 <html> 元素添加自定义类名 */
className?: string;
};

type VersionsConfig = {[versionName: string]: VersionConfig};

示例配置

您可以通过预设选项或插件选项配置此插件。

提示

大多数 Docusaurus 用户通过预设选项配置此插件。

If you use a preset, configure this plugin through the preset options:

docusaurus.config.js
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
[translation failure]: {
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,
}) {
// Use the provided data to generate a custom sidebar slice
return [
{type: 'doc', id: 'intro'},
{
type: 'category',
label: 'Tutorials',
items: [
{type: 'doc', id: 'tutorial1'},
{type: 'doc', id: 'tutorial2'},
],
},
];
},
numberPrefixParser(filename) {
// Implement your own logic to extract a potential number prefix
const numberPrefix = findNumberPrefix(filename);
// Prefix found: return it with the cleaned filename
if (numberPrefix) {
return {
numberPrefix,
filename: filename.replace(prefix, ''),
};
}
// No number prefix found
return {numberPrefix: undefined, filename};
},
docsRootComponent: '@theme/DocsRoot',
docVersionRootComponent: '@theme/DocVersionRoot',
docRootComponent: '@theme/DocRoot',
docItemComponent: '@theme/DocItem',
remarkPlugins: [require('./my-remark-plugin')],
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 front matter

Markdown documents can use the following Markdown front matter metadata fields, enclosed by a line --- on either side.

Accepted fields:

NameTypeDefaultDescription
idstringfile path (including folders, without the extension)A unique document ID.
titlestringMarkdown title or idThe text title of your document. Used for the page metadata and as a fallback value in multiple places (sidebar, next/previous buttons...). Automatically added at the top of your doc if it does not contain any Markdown title.
pagination_labelstringsidebar_label or titleThe text used in the document next/previous buttons for this document.
displayed_sidebarstringundefinedForce the display of a given sidebar when browsing the current document. Read the multiple sidebars guide for details.
hide_titlebooleanfalseWhether to hide the title at the top of the doc. It only hides a title declared through the front matter, and have no effect on a Markdown title at the top of your document.
hide_table_of_contentsbooleanfalseWhether to hide the table of contents to the right.
toc_min_heading_levelnumber2The minimum heading level shown in the table of contents. Must be between 2 and 6 and lower or equal to the max value.
toc_max_heading_levelnumber3The max heading level shown in the table of contents. Must be between 2 and 6.
pagination_nextstring | nullNext doc in the sidebarThe ID of the documentation you want the "Next" pagination to link to. Use null to disable showing "Next" for this page.
pagination_prevstring | nullPrevious doc in the sidebarThe ID of the documentation you want the "Previous" pagination to link to. Use null to disable showing "Previous" for this page.
parse_number_prefixesbooleannumberPrefixParser plugin optionWhether number prefix parsing is disabled on this doc. See also Using number prefixes.
custom_edit_urlstring | nullComputed using the editUrl plugin optionThe URL for editing this document. Use null to disable showing "Edit this page" for this page.
keywordsstring[]undefinedKeywords meta tag for the document page, for search engines.
descriptionstringThe first line of Markdown contentThe description of your document, which will become the <meta name="description" content="..."/> and <meta property="og:description" content="..."/> in <head>, used by search engines.
imagestringundefinedCover or thumbnail image that will be used as the <meta property="og:image" content="..."/> in the <head>, enhancing link previews on social media and messaging platforms.
slugstringFile pathAllows to customize the document URL (/<routeBasePath>/<slug>). Support multiple patterns: slug: my-doc, slug: /my/path/myDoc, slug: /.
tagsTag[]undefinedA list of strings or objects of two string fields label and permalink to tag to your docs. Strings can be a reference to keys of a tags file (usually tags.yml)
draftbooleanfalseDraft documents will only be available during development.
unlistedbooleanfalseUnlisted documents will be available in both development and production. They will be "hidden" in production, not indexed, excluded from sitemaps, and can only be accessed by users having a direct link.
last_updateFrontMatterLastUpdateundefinedAllows overriding the last update author/date. Date can be any parsable date string.
type FrontMatterLastUpdate = {date?: string; author?: string};

type Tag = string | {label: string; permalink: string};

Example:

---
id: doc-markdown
title: Docs Markdown Features
hide_title: false
hide_table_of_contents: false
sidebar_label: Markdown
sidebar_position: 3
pagination_label: Markdown features
custom_edit_url: https://github.com/facebook/docusaurus/edit/main/docs/api-doc-markdown.md
description: How do I find you when I cannot solve this problem
keywords:
- docs
- docusaurus
tags: [docusaurus]
image: https://i.imgur.com/mErPwqL.png
slug: /myDoc
last_update:
date: 1/1/2000
author: custom author name
---

# Markdown Features

My Document Markdown content

标签文件

使用 tags 插件选项 配置 YAML 标签文件的路径。

按照约定,插件将在内容文件夹的根目录下查找 tags.yml 文件。

此文件可以包含预定义标签的列表。您可以在 Markdown 文件中通过 tags 前置元数据引用这些标签的键。

保持标签一致性

使用标签文件,您可以确保在插件内容集中标签的使用是一致的。使用 onInlineTags: 'throw' 插件选项来强制执行这种一致性,并防止使用临时声明的内联标签。

类型

提供的标签文件的 YAML 内容应遵循以下结构:

type Tag = {
label?: string; // 标签显示标签
permalink?: string; // 标签 URL 路径名段
description?: string; // 标签页面中显示的标签描述
};

type TagsFileInput = Record<string, Partial<Tag> | null>;

示例

tags.yml
releases:
label: '产品发布'
permalink: '/product-releases'
description: '与产品发布相关的内容。'

# 部分标签定义也是有效的
announcements:
label: '公告'

# 空标签定义也是有效的
# 其他属性将从键推断
emptyTag:
content.md
---
tags: [releases, announcements, emptyTag]
---

# 标题

内容

i18n

Read the i18n introduction first.

Translation files location

  • Base path: website/i18n/[locale]/docusaurus-plugin-content-docs
  • Multi-instance path: website/i18n/[locale]/docusaurus-plugin-content-docs-[pluginId]
  • JSON files: extracted with docusaurus write-translations
  • Markdown files: website/i18n/[locale]/docusaurus-plugin-content-docs/[versionName]

Example file-system structure

website/i18n/[locale]/docusaurus-plugin-content-docs

# translations for website/docs
├── current
│ ├── api
│ │ └── config.md
│ └── getting-started.md
├── current.json

# translations for website/versioned_docs/version-1.0.0
├── version-1.0.0
│ ├── api
│ │ └── config.md
│ └── getting-started.md
└── version-1.0.0.json