Skip to main content

Autogenerated

Docusaurus 可以根据文件系统自动生成 sidebar, 每个文件夹创建一个sidebar分组, 每个文件创建一个文档链接.

比如配置:

sidebars.js
module.exports = {
myAutogeneratedSidebar: [
{
type: 'autogenerated',
dirName: '.', // '.' means the current docs folder
},
],
};

Category index convention

Docusaurus基于一下约定, 自动给分组关联首页文档:

  • 文件名为index(区分大小写), 比如: docs/Guides/index.md
  • 文件名为README(区分大小写), 比如: docs/Guides/README.mdx
  • 和文件夹同名的文件名, 比如: docs/Guides/Guides.md

等价的方式是使用配置给分组指定文档链接:

sidebars.js
module.exports = {
docs: [
{
type: 'category',
label: 'Guides',
link: {type: 'doc', id: 'Guides/index'},
items: [],
},
],
};

Customizing category index matching

你可以通过提供sidebarItemsGenerator回调函数注入自己的isCategoryIndex匹配规则:

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
async sidebarItemsGenerator({
...args,
isCategoryIndex: defaultCategoryIndexMatcher, // The default matcher implementation, given below
defaultSidebarItemsGenerator,
}) {
return defaultSidebarItemsGenerator({
...args,
isCategoryIndex(doc) {
return (
// Also pick intro.md in addition to the default ones
doc.fileName.toLowerCase() === 'intro' ||
defaultCategoryIndexMatcher(doc)
);
},
});
},
},
],
],
};

isCategoryIndex匹配器提供三个字段:

  • fileName, 不包含扩展名的文件名(保留了文件名大小写)
  • directories, 相对于根目录的目录层级列表(小写)
  • extension 文件扩展名(包含 .)

对于文件 docs/guides/sidebar/autogenerated.md, 上述三个字段值为:

const props = {
fileName: 'autogenerated',
directories: ['sidebar', 'guides'],
extension: '.md',
};

Autogenerated sidebar metadata

默认情况下, 自动生成文件的顺序按照文件名或者文件夹名的字母表顺序排序.

Doc item metadata

sidebar.js中每个sidebar的三个属性: label, className, customProps 分别对应文档元数据中的 sidebar_label, sidebar_class_name, sidebar_custom_props, 而位置对应 sidebar_position:

docs/tutorials/tutorial-easy.md
---
sidebar_position: 2
sidebar_label: Easy
sidebar_class_name: green
---

# Easy Tutorial

This is the easy tutorial!

Category item metadata

在对应文件夹增加 _category_.json 或者 _category_.yml 文件, 也可以指定文档sidebar分组的元数据(包括位置):

docs/tutorials/_category_.json
{
"position": 2.5,
"label": "Tutorial",
"collapsible": true,
"collapsed": false,
"className": "red",
"link": {
"type": "generated-index",
"title": "Tutorial overview"
},
"customProps": {
"description": "This description can be used in the swizzled DocCard"
}
}

或者使用YAML格式:

docs/tutorials/_category_.yml
position: 2.5 # float position is supported
label: 'Tutorial'
collapsible: true # make the category collapsible
collapsed: false # keep the category open by default
className: red
link:
type: generated-index
title: Tutorial overview
customProps:
description: This description can be used in the swizzled DocCard

Using number prefixes

也可以在文件夹、文件名增加数字前缀修改默认排序:

docs
├── 01-Intro.md
├── 02-Tutorial Easy
│ ├── 01-First Part.md
│ ├── 02-Second Part.md
│ └── 03-End.md
├── 03-Tutorial Hard
│ ├── 01-First Part.md
│ ├── 02-Second Part.md
│ ├── 03-Third Part.md
│ └── 04-End.md
└── 04-End.md