跳到主要内容
版本:Canary 🚧

📦 plugin-content-docs

Provides the Docs functionality and is the default docs plugin for Docusaurus.

安装流程

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

如果你已经安装了 @docusaurus/preset-classic,就不需要安装这个包了。

You can configure this plugin through the preset options.

配置

接受的字段:

参数类型默认值描述
pathstring'docs'文档内容目录的文件系统路径,相对于站点目录。
editUrlstring | EditUrlFunctionundefined编辑文档的基础 URL。 最终的 URL 会按照 editUrl + relativeDocPath 计算。 使用函数可以允许你更精细地控制每一个文件。 完全忽略这个变量就会禁用编辑链接。
editLocalizedFilesbooleanfalse编辑 URL 会指向本地化的文件,而不是原始的未翻译文件。 如果 editUrl 是一个函数,会完全忽略此选项。
editCurrentVersionbooleanfalse编辑 URL 会永远指向当前版本文档而不是历史版本。 如果 editUrl 是一个函数,会完全忽略此选项。
routeBasePathstring'docs'站点文档部分的 URL 前缀。 不要包含末尾斜杠。 如果要部署没有基础路径的文档,请使用 /
tagsBasePathstring'tags'站点标签列表部分的 URL 前缀。 会被添加到 routeBasePath 后面。
includestring[]['**/*.{md,mdx}']相对于内容路径的 glob 模式列表,匹配到的 Markdown 文件会被构建。
excludestring[]见示例配置Glob 模式列表,匹配到的 Markdown 文件会被排除。 在 include 选项的基础上进一步细调。
sidebarPathfalse | stringundefined侧边栏配置的路径。 false 会禁用侧边栏,undefined 会创建一个完全自动生成的侧边栏。
sidebarCollapsiblebooleantrue侧边栏类别是否默认可折叠。 See also Collapsible categories
sidebarCollapsedbooleantrue侧边栏类别是否默认被折叠。 See also Expanded categories by default
sidebarItemsGeneratorSidebarGenerator用于将 'autogenerated' 类型的侧边栏项目替换为真正的侧边栏项(文档、类别、链接……)的函数。 See also Customize the sidebar items generator
numberPrefixParserboolean | PrefixParser自定义从文件名中提取数字前缀的逻辑。 false 会禁用这种行为并保持文件名不变,true 会使用默认的解析器。 See also Using number prefixes
docsRootComponentstring'@theme/DocsRoot'Parent component of all the docs plugin pages (including all versions). Stays mounted when navigation between docs pages and versions.
docVersionRootComponentstring'@theme/DocVersionLayout'Parent component of all docs pages of an individual version (doc pages with sidebars, tags pages). Stays mounted when navigation between pages of that specific version.
docRootComponentstring'@theme/DocPage'Parent component of all doc pages with sidebars (regular docs pages, category generated index pages). Stays mounted when navigation between such pages.
docItemComponentstring'@theme/DocItem'文档主容器,包括了目录、页面导航等。
docTagsListComponentstring'@theme/DocTagsListPage'标签列表页的根组件
docTagDocListComponentstring'@theme/DocTagDocListPage'「包含某标签的所有文档」页面的根组件。
docCategoryGeneratedIndexComponentstring'@theme/DocCategoryGeneratedIndexPage'自动生成类别索引页的根组件。
remarkPluginsany[][]传递给 MDX 的 Remark 插件。
rehypePluginsany[][]传递给 MDX 的 Rehype 插件。
beforeDefaultRemarkPluginsany[][]在 Docusaurus 默认 Remark 插件之前传递给 MDX 的自定义 Remark 插件。
beforeDefaultRehypePluginsany[][]在 Docusaurus 默认 Rehype 插件之前传递给 MDX 的自定义 Rehype 插件。
showLastUpdateAuthorbooleanfalse是否显示最后更新文档的作者。
showLastUpdateTimebooleanfalseWhether to display the last date the doc was updated. This requires access to git history during the build, so will not work correctly with shallow clones (a common default for CI systems). With GitHub actions/checkout, usefetch-depth: 0.
disableVersioningbooleanfalse即使存在多个版本,也明确禁用分版功能。 这会让网站只包含当前版本。 如果 includeCurrentVersion: false 并且 disableVersioning: true,会报错。
includeCurrentVersionbooleantrue包含文档的当前版本。
lastVersionstringversions.json 中的第一个版本文档类的导航栏项会默认显示并跳转到的文档版本。
onlyIncludeVersionsstring[]所有版本只包含所有可用版本中的一个子集。
versionsVersionsConfig{}独立自定义每个版本的属性。

类型

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 用户通过预设选项配置此插件。

如果你使用预设,你可以通过预设选项配置这个插件:

docusaurus.config.js
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
path: 'docs',
breadcrumbs: true,
// Simple use-case: string editUrl
// editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/',
// Advanced use-case: functional 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 前言

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

接受的字段:

参数类型默认值描述
idstring文件路径(包括文件夹,不含扩展名)文档的唯一 ID。
titlestringMarkdown 标题或 id你的文档使用的文本标题。 用于页面元数据和多个地方的备用值(侧边栏、下篇/上篇按钮……)。 如果 Markdown 内容没有标题,它会被自动添加到你的文档顶部。
pagination_labelstringsidebar_labeltitle这篇文档在上一篇/下一篇按钮中显示的文本
displayed_sidebarstringundefinedForce the display of a given sidebar when browsing the current document. Read the multiple sidebars guide for details.
hide_titlebooleanfalse是否隐藏文档顶部显示的标题。 此选项只会隐藏前言中定义的标题,对于 Markdown 文档顶部的标题没有任何影响。
hide_table_of_contentsbooleanfalse是否隐藏右侧的文档目录。
toc_min_heading_levelnumber2目录中显示的最小标题层级。 必须介于 2 到 6 之间,并且小于等于最大值。
toc_max_heading_levelnumber3目录中显示的最大标题层级。 必须介于 2 和 6。
pagination_nextstring | null侧边栏的下一个文档「下篇文档」按钮链接到的文档 ID。 null 会禁用本页的「下篇文档」按钮。
pagination_prevstring | null侧边栏的上一个文档「上篇文档」按钮链接到的文档 ID。 null 会禁用本页的「上篇文档」按钮。
parse_number_prefixesbooleannumberPrefixParser 插件选项是否禁用本文档的数字前缀解析。 See also Using number prefixes.
custom_edit_urlstring | null使用 editUrl 插件选项计算编辑此文档时要跳转到的 URL。 Use null to disable showing "Edit this page" for this page.
keywordsstring[]undefined用于搜索引擎优化的文档关键词元标签。
descriptionstringMarkdown 正文的第一行文档的描述信息,会生成 <head> 中被搜索引擎读取的 <meta name="description" content="..."/><meta property="og:description" content="..."/>
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.
slugstring文件路径自定义文档的 URL (/<routeBasePath>/<slug>)。 支持多种形式: slug: my-docslug: /my/path/myDocslug: /
tagsTag[]undefined一个列表,由字符串或者包含 labelpermalink 字符串字段的对象构成,用于提供文档标签。
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. 日期可以是任意可解析的日期字符串
type FrontMatterLastUpdate = {date?: string; author?: string};

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

示例:

---
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
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

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/[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