跳到主要内容
版本:Canary 🚧

📦 plugin-content-docs

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

安装

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

如果你使用预设的@docusaurus/preset-classic,你不需要将这个插件作为依赖项安装。

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

配置

接受字段:

名字类型默认的描述
pathstring'docs'文件系统中 docs 内容目录的路径,相对于站点目录。
editUrlstring | EditUrlFunctionundefined用于编辑站点的基础 URL。最终的 URL 由editUrl + relativeDocPath计算。使用函数可以对每个文件进行更细致的控制。完全省略这个变量将禁用编辑链接。
editLocalizedFilesbooleanfalse编辑 URL 将针对已本地化的文件,而不是原始的未本地化文件。当editUrl是函数时忽略。
editCurrentVersionbooleanfalse编辑 URL 将始终针对当前版本文档,而不是旧版本。当editUrl是函数时忽略。
routeBasePathstring'docs'网站文档部分的 URL 路由。不要包含尾斜杠。对于没有基本路径的 shipping docs 使用/
tagsBasePathstring'tags'您网站的标签列表页面的 URL 路由。它被附加到routeBasePath
includestring[]['**/*.{md,mdx}']与要构建的 Markdown 文件相匹配的全局模式数组,相对于内容路径。
excludestring[]See example configuration匹配要排除的降级文件的全局模式数组。作为基于include选项的细化。
sidebarPathfalse | stringundefined到侧栏配置的路径。使用false来禁用侧边栏,或使用undefined来创建完全自动生成的侧边栏。
sidebarCollapsiblebooleantrue默认情况下,侧栏类别是否可折叠。参见可折叠的类别
sidebarCollapsedbooleantrue默认情况下,侧边栏类别是否折叠。参见默认展开的类别
sidebarItemsGeneratorSidebarGeneratorOmitted函数用于将'autogenerated'类型的侧边栏项替换为真正的侧边栏项(文档、类别、链接…)。参见自定义侧边栏项生成器
numberPrefixParserboolean | PrefixParserOmitted自定义解析逻辑从文件名中提取数字前缀。使用false来禁用此行为并保持文档不变,使用true来使用默认解析器。参见使用数字前缀
docsRootComponentstring'@theme/DocsRoot'所有文档插件页面(包括所有版本)的父组件。在文档页面和版本之间导航时保持挂载状态。
docVersionRootComponentstring'@theme/DocVersionLayout'单个版本中所有文档页面的父组件(带有侧边栏的文档页面、标签页面)。在该特定版本的页面之间导航时保持挂载状态。
docRootComponentstring'@theme/DocPage'所有带侧边栏的文档页面的父组件(常规文档页面,分类生成的索引页面)。在这些页面之间导航时保持挂载状态。
docItemComponentstring'@theme/DocItem'主文档容器,具有 TOC,分页等。
docTagsListComponentstring'@theme/DocTagsListPage'标签列表页面的根组件
docTagDocListComponentstring'@theme/DocTagDocListPage'"docs contains tag X"页面的根组件。
docCategoryGeneratedIndexComponentstring'@theme/DocCategoryGeneratedIndexPage'生成的类别索引页的根组件。
remarkPluginsany[][]Remark 插件传递给 MDX。
rehypePluginsany[][]Rehype 插件传递给 MDX。
beforeDefaultRemarkPluginsany[][]在默认 Docusaurus Remark 插件之前传递给 MDX 的自定义 Remark 插件。
beforeDefaultRehypePluginsany[][]自定义 Rehype 插件在默认 Docusaurus Rehype 插件之前传递给 MDX。
showLastUpdateAuthorbooleanfalse是否显示最后更新文档的作者。
showLastUpdateTimebooleanfalse是否显示文档最后更新的日期。
disableVersioningbooleanfalse即使存在多个版本,也要显式禁用版本控制。这将使网站只包括当前版本。如果includeCurrentVersion: falsedisableVersioning: true将会出错。
includeCurrentVersionbooleantrue包含当前版本的文档。
lastVersionstringFirst version in versions.json文档导航栏项导航到的优先级和默认显示的版本。
onlyIncludeVersionsstring[]All versions available只包含所有可用版本的子集。
versionsVersionsConfig{}独立定制每个版本的属性。

Types

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: {
/** The sidebar item with type "autogenerated" to be transformed. */
item: { type: "autogenerated"; dirName: string };
/** Useful metadata for the version this sidebar belongs to. */
version: { contentPath: string; versionName: string };
/** All the docs of that version (unfiltered). */
docs: {
id: string;
title: string;
frontMatter: DocFrontMatter & Record<string, unknown>;
source: string;
sourceDirName: string;
sidebarPosition?: number | undefined;
}[];
/** Number prefix parser configured for this plugin. */
numberPrefixParser: PrefixParser;
/** The default category index matcher which you can override. */
isCategoryIndex: CategoryIndexMatcher;
/**
* key is the path relative to the doc content directory, value is the
* category metadata file's content.
*/
categoriesMetadata: { [filePath: string]: CategoryMetadata };
/**
* Useful to re-use/enhance the default sidebar generation logic from
* Docusaurus.
*/
defaultSidebarItemsGenerator: SidebarGenerator;
// Returns an array of sidebar items — same as what you can declare in
// sidebars.js, except for shorthands. See https://docusaurus.io/docs/sidebar/items
}) => Promise<SidebarItem[]>;

type CategoryIndexMatcher = (param: {
/** The file name, without extension */
fileName: string;
/**
* The list of directories, from lowest level to highest.
* If there's no dir name, directories is ['.']
*/
directories: string[];
/** The extension, with a leading dot */
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 };
},
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 文档可以使用以下 Markdown 元数据元数据字段,在两边用一行---括起来。

接受字段:

名字类型默认描述
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 when displaying the link to your post.
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.
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_updateFileChangeundefinedAllows overriding the last updated author and/or date. Date can be any parsable date string.
type Tag = string | { label: string; permalink: string };
type FileChange = { date: string; author: 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

首先阅读i18n 介绍

翻译文件位置

  • 基本路径: website/i18n/[locale]/docusaurus-plugin-content-docs
  • 多实例路径: website/i18n/[locale]/docusaurus-plugin-content-docs-[pluginId]
  • JSON 文件: 提取自docusaurus write-translations
  • Markdown 文件: website/i18n/[locale]/docusaurus-plugin-content-docs/[versionName]

示例文件系统结构

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