Aller au contenu principal
Version : 2.4.0

Autogenerated

Docusaurus can create a sidebar automatically from your filesystem structure: each folder creates a sidebar category, and each file creates a doc link.

type SidebarItemAutogenerated = {
type: 'autogenerated';
dirName: string; // Dossier source pour générer la barre latérale (relative à docs)
};

Docusaurus peut générer une barre latérale complète à partir de votre dossier docs :

sidebars.js
module.exports = {
myAutogeneratedSidebar: [
{
type: 'autogenerated',
dirName: '.', // '.' signifie le dossier docs courant
},
],
};

An autogenerated item is converted by Docusaurus to a sidebar slice (also discussed in category shorthands): a list of items of type doc or category, so you can splice multiple autogenerated items from multiple directories, interleaving them with regular sidebar items, in one sidebar level.

A real-world example

Considérer cette structure de fichiers :

docs
├── api
│ ├── product1-api
│ │ └── api.md
│ └── product2-api
│ ├── basic-api.md
│ └── pro-api.md
├── intro.md
└── tutorials
├── advanced
│ ├── advanced1.md
│ ├── advanced2.md
│ └── read-more
│ ├── resource1.md
│ └── resource2.md
├── easy
│ ├── easy1.md
│ └── easy2.md
├── tutorial-end.md
├── tutorial-intro.md
└── tutorial-medium.md

Supposons que chaque identifiant de la documentation ne soit que son nom de fichier. Si vous définissez une barre latérale générée automatiquement comme ceci :

sidebars.js
module.exports = {
mySidebar: [
'intro',
{
type: 'category',
label: 'Tutorials',
items: [
'tutorial-intro',
{
type: 'autogenerated',
dirName: 'tutorials/easy', // Génère une barre latérale à partir de docs/tutorials/easy
},
'tutorial-medium',
{
type: 'autogenerated',
dirName: 'tutorials/advanced', // Génère une barre latérale à partir de docs/tutorials/hard
},
'tutorial-end',
],
},
{
type: 'autogenerated',
dirName: 'api', // Génère une barre latérale à partir de docs/api
},
{
type: 'category',
label: 'Community',
items: ['team', 'chat'],
},
],
};

Elle serait résolue ainsi :

sidebars.js
module.exports = {
mySidebar: [
'intro',
{
type: 'category',
label: 'Tutorials',
items: [
'tutorial-intro',
// Deux fichiers dans docs/tutorials/easy
'easy1',
'easy2',
'tutorial-medium',
// Deux fichiers et un dossier dans docs/tutorials/hard
'advanced1',
'advanced2',
{
type: 'category',
label: 'read-more',
items: ['resource1', 'resource2'],
},
'tutorial-end',
],
},
// Deux dossiers dans docs/api
{
type: 'category',
label: 'product1-api',
items: ['api'],
},
{
type: 'category',
label: 'product2-api',
items: ['basic-api', 'pro-api'],
},
{
type: 'category',
label: 'Community',
items: ['team', 'chat'],
},
],
};

Notez que les répertoires de sources générés automatiquement ne deviennent pas des catégories : seuls les éléments qu'ils contiennent le sont. C'est ce que nous entendons par « section de barre latérale ».

Category index convention

Docusaurus peut lier automatiquement une catégorie à son document d'index.

Un document d'index de catégorie est un document qui suit l'une de ces conventions de nom de fichier :

  • Named as index (case-insensitive): docs/Guides/index.md
  • Named as README (case-insensitive): docs/Guides/README.mdx
  • Same name as parent folder: docs/Guides/Guides.md

This is equivalent to using a category with a doc link:

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

Naming your introductory document README.md makes it show up when browsing the folder using the GitHub interface, while using index.md makes the behavior more in line with how HTML files are served.

astuce

Si un dossier n'a qu'une page d'index, il sera transformé en lien au lieu d'une catégorie. This is useful for asset collocation:

some-doc
├── index.md
├── img1.png
└── img2.png
Customizing category index matching

Il est possible d'exclure n'importe laquelle des conventions de l'index des catégories, ou de définir encore plus de conventions. You can inject your own isCategoryIndex matcher through the sidebarItemsGenerator callback. For example, you can also pick intro as another file name eligible for automatically becoming the category index.

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
async sidebarItemsGenerator({
...args,
isCategoryIndex: defaultCategoryIndexMatcher, // L'implémentation par défaut du sélecteur, donnée ci-dessous
defaultSidebarItemsGenerator,
}) {
return defaultSidebarItemsGenerator({
...args,
isCategoryIndex(doc) {
return (
// Choisissez également intro.md en plus de ceux par défaut
doc.fileName.toLowerCase() === 'intro' ||
defaultCategoryIndexMatcher(doc)
);
},
});
},
},
],
],
};

Ou choisir de ne pas avoir de convention d'index de catégorie.

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
async sidebarItemsGenerator({
...args,
isCategoryIndex: defaultCategoryIndexMatcher, // L'implémentation par défaut du sélecteur, donnée ci-dessous
defaultSidebarItemsGenerator,
}) {
return defaultSidebarItemsGenerator({
...args,
isCategoryIndex() {
// Aucun doc ne sera automatiquement choisi comme index de catégorie
return false;
},
});
},
},
],
],
};

The isCategoryIndex matcher will be provided with three fields:

  • fileName, the file's name without extension and with casing preserved
  • directories, the list of directory names from the lowest level to the highest level, relative to the docs root directory
  • extension, the file's extension, with a leading dot.

For example, for a doc file at guides/sidebar/autogenerated.md, the props the matcher receives are

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

L'implémentation par défaut est :

function isCategoryIndex({fileName, directories}) {
const eligibleDocIndexNames = [
'index',
'readme',
directories[0].toLowerCase(),
];
return eligibleDocIndexNames.includes(fileName.toLowerCase());
}

Autogenerated sidebar metadata

For handwritten sidebar definitions, you would provide metadata to sidebar items through sidebars.js; for autogenerated, Docusaurus would read them from the item's respective file. In addition, you may want to adjust the relative position of each item because, by default, items within a sidebar slice will be generated in alphabetical order (using file and folder names).

Doc item metadata

The label, className, and customProps attributes are declared in front matter as sidebar_label, sidebar_class_name, and sidebar_custom_props, respectively. Position can be specified in the same way, via sidebar_position front matter.

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

# Tutoriel facile

C'est le tutoriel facile !

Category item metadata

Add a _category_.json or _category_.yml file in the respective folder. You can specify any category metadata and also the position metadata. label, className, position, and customProps will default to the respective values of the category's linked doc, if there is one.

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"
}
}
info

If the link is explicitly specified, Docusaurus will not apply any default conventions.

The doc links can be specified relatively, e.g. if the category is generated with the guides directory, "link": {"type": "doc", "id": "intro"} will be resolved to the ID guides/intro, only falling back to intro if a doc with the former ID doesn't exist.

You can also use link: null to opt out of default conventions and not generate any category index page.

info

The position metadata is only used within a sidebar slice: Docusaurus does not re-order other items of your sidebar.

Using number prefixes

Une façon simple d'ordonner une barre latérale générée automatiquement est de préfixer les documents et les dossiers par des préfixes numériques, ce qui les fait également apparaître dans le système de fichiers dans le même ordre lorsqu'ils sont triés par nom de fichier :

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

To make it easier to adopt, Docusaurus supports multiple number prefix patterns.

By default, Docusaurus will remove the number prefix from the doc id, title, label, and URL paths.

attention

Prefer using additional metadata.

Updating a number prefix can be annoying, as it can require updating multiple existing Markdown links:

docs/02-Tutorial Easy/01-First Part.md
- Check the [Tutorial End](../04-End.mdx);
+ Check the [Tutorial End](../05-End.mdx);

Customize the sidebar items generator

You can provide a custom sidebarItemsGenerator function in the docs plugin (or preset) config:

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
async sidebarItemsGenerator({
defaultSidebarItemsGenerator,
numberPrefixParser,
item,
version,
docs,
categoriesMetadata,
isCategoryIndex,
}) {
// Exemple : retourne une liste codée en dur des éléments statiques de la barre latérale
return [
{type: 'doc', id: 'doc1'},
{type: 'doc', id: 'doc2'},
];
},
},
],
],
};
astuce

Re-use and enhance the default generator instead of writing a generator from scratch: the default generator we provide is 250 lines long.

Add, update, filter, re-order the sidebar items according to your use case:

docusaurus.config.js
// Reverse the sidebar items ordering (including nested category items)
function reverseSidebarItems(items) {
// Reverse items in categories
const result = items.map((item) => {
if (item.type === 'category') {
return {...item, items: reverseSidebarItems(item.items)};
}
return item;
});
// Reverse items at current level
result.reverse();
return result;
}

module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
async sidebarItemsGenerator({defaultSidebarItemsGenerator, ...args}) {
const sidebarItems = await defaultSidebarItemsGenerator(args);
return reverseSidebarItems(sidebarItems);
},
},
],
],
};