Barra Lateral
Criar uma barra lateral é útil para:
- Agrupar vários documentos relacionados
- Exibe uma barra lateral em cada um desses documentos
- Forneça uma navegação paginada, com o botão seguinte/anterior
Para usar as barras laterais no seu site do Docusaurus:
- Define um arquivo que exporta um objeto da barra lateral.
- Passe esse objeto no plugin
@docusaurus/plugin-docs
diretamente ou via@docusaurus/preset-classic
.
module.exports = { presets: [ [ '@docusaurus/preset-classic', { docs: { sidebarPath: require.resolve('./sidebars.js'), }, }, ], ],};
#
Barra lateral padrãoPor padrão, o Docusaurus gera automaticamente uma barra lateral para você, usando a estrutura do sistema de arquivos da pasta docs
:
module.exports = { mySidebar: [ { type: 'autogenerated', dirName: '.', // generate sidebar slice from the docs folder (or versioned_docs/<version>) }, ],};
Você também pode definir suas barras laterais explicitamente.
#
Objeto de barra lateralUma barra lateral é uma árvore de itens na barra lateral.
type Sidebar = // Normal syntax | SidebarItem[]
// Shorthand syntax | Record< string, // category label SidebarItem[] // category items >;
Um arquivo de barras laterais pode conter múltiplos objetos da barra lateral.
type SidebarsFile = Record< string, // sidebar id Sidebar>;
Exemplo:
module.exports = { mySidebar: [ { type: 'category', label: 'Getting Started', items: ['doc1'], }, { type: 'category', label: 'Docusaurus', items: ['doc2', 'doc3'], }, ],};
Observe o seguinte:
- Há uma única barra lateral
mySidebar
, contendo 5 itens de barra lateral Primeiros passos
eo Docusaurus
são categorias de barra lateraldoc1
,doc2
edoc3
são documentos de barra lateral
tip
Use a sintaxe curta **** para expressar essa barra lateral de forma mais concisa:
module.exports = { mySidebar: { 'Getting started': ['doc1'], Docusaurus: ['doc2', 'doc3'], },};
#
Usando múltiplas barras lateraisVocê pode criar uma barra lateral para cada conjunto de arquivos Markdown que você deseja agrupar todos.
Exemplo:
module.exports = { tutorialSidebar: { 'Category A': ['doc1', 'doc2'], }, apiSidebar: ['doc3', 'doc4'],};
note
As chaves tutorialSidebar
e apiSidebar
são barras laterais Ids técnicas e não importam muito.
Ao navegar:
doc1
oudoc2
: otutorialSidebar
será exibidodoc3
oudoc4
: aapiSidebar
será exibida
Um paginado de navegação link dentro da mesma barra lateral com botões seguinte e anterior.
#
Entendendo itens da barra lateralSidebarItem
é um item definido em uma árvore lateral.
Existem diferentes tipos de itens na barra lateral:
- Doc: link para uma página de documento, atribuindo-o à barra lateral
- Ref: link para uma página de um documento sem atribuí-lo à barra lateral
- Link: link para qualquer página interna ou externa
- Categoria: crie uma hierarquia de itens da barra lateral
- Gerada automaticamente: gerar um recorte de barra lateral automaticamente
#
Doc: link para um documentoUse o tipo doc
para criar um link para uma página de documento e atribuir esse documento a uma barra lateral:
type SidebarItemDoc = // Normal syntax | { type: 'doc'; id: string; label: string; // Sidebar label text }
// Shorthand syntax | string; // docId shortcut
Exemplo:
module.exports = { mySidebar: [ // Normal syntax: { type: 'doc', id: 'doc1', // document id label: 'Getting started', // sidebar label },
// Shorthand syntax: 'doc2', // document id ],};
O frontmatter de markdown sidebar_label
tem uma precedência mais alta sobre a chave label
em SidebarItemDoc
.
note
Não atribua o mesmo documento a várias barras laterais: use um ref.
#
Ref.: link para um doc, sem barra lateralUse o tipo ref
para vincular a uma página de documento sem atribuí-lo a uma barra lateral.
type SidebarItemRef = { type: 'ref'; id: string;};
Exemplo:
module.exports = { mySidebar: [ { type: 'ref', id: 'doc1', // Document id (string). }, ],};
Ao navegar pela doc1
, o Docusaurus não mostrará a barra lateral mySidebar
.
#
Link: link para qualquer páginaUse o tipo link
para vincular qualquer página (interna ou externa) que não seja um doc.
type SidebarItemLink = { type: 'link'; label: string; href: string;};
Exemplo:
module.exports = { myLinksSidebar: [ // External link { type: 'link', label: 'Facebook', // The link label href: 'https://facebook.com', // The external URL },
// Internal link { type: 'link', label: 'Home', // The link label href: '/', // The internal path }, ],};
#
Categoria: criar uma hierarquiaUse o tipo categoria
para criar uma hierarquia de itens da barra lateral.
type SidebarItemCategory = { type: 'category'; label: string; // Sidebar label text. items: SidebarItem[]; // Array of sidebar items.
// Opções de categoria: collapsible: boolean; // Defina a categoria para ser recolhida collapsed: boolean; // Defina a categoria a ser inicialmente recolhida ou aberta por padrão};
Exemplo:
module.exports = { docs: [ { type: 'category', label: 'Guides', collapsible: true, collapsed: false, items: [ 'creating-pages', { type: 'category', label: 'Docs', items: ['introduction', 'sidebar', 'markdown-features', 'versioning'], }, ], }, ],};
tip
Use a sintaxe abreviada quando não precisar das opções de categoria:
module.exports = { docs: { Guides: [ 'creating-pages', { Docs: ['introduction', 'sidebar', 'markdown-features', 'versioning'], }, ], },};
#
Categorias recolhíveisWe support the option to expand/collapse categories. Categories are collapsible by default, but you can disable collapsing with collapsible: false
.
module.exports = { docs: [ { type: 'category', label: 'Guides', items: [ 'creating-pages', { type: 'category', collapsible: false, label: 'Docs', items: ['introduction', 'sidebar', 'markdown-features', 'versioning'], }, ], }, ],};
To make all categories non-collapsible by default, set the sidebarCollapsible
option in plugin-docs
to false
:
module.exports = { presets: [ [ '@docusaurus/preset-classic', { docs: { sidebarCollapsible: false, }, }, ], ],};
note
The option in sidebars.js
takes precedence over plugin configuration, so it is possible to make certain categories collapsible when sidebarCollapsible
is set to false
globally.
#
Categorias expandidas por padrãoCollapsible categories are collapsed by default. If you want them to be expanded on first render, you can set collapsed
to false
:
module.exports = { docs: { Guides: [ 'creating-pages', { type: 'category', label: 'Docs', collapsed: false, items: ['markdown-features', 'sidebar', 'versioning'], }, ], },};
Similar to collapsible
, you can also set the global configuration options.sidebarCollapsed
to false
. Individual collapsed
options in sidebars.js
will still take precedence over this configuration.
module.exports = { presets: [ [ '@docusaurus/preset-classic', { docs: { sidebarCollapsed: false, }, }, ], ],};
caution
When a category has collapsed: true
but collapsible: false
(either through sidebars.js
or through plugin configuration), the latter takes precedence and the category is still rendered as expanded.
#
Autogerado: gerar uma barra lateralDocusaurus pode criar uma barra lateral automaticamente a partir de sua estrutura do sistema de arquivos: cada pasta cria uma categoria da barra lateral.
Um item autogenerated
é convertido pelo Docusaurus em uma fatia da barra lateral : uma lista de itens do tipo doc
e categoria
.
type SidebarItemAutogenerated = { type: 'autogenerated'; dirName: string; // Source folder to generate the sidebar slice from (relative to docs)};
O Docusaurus pode gerar uma barra lateral a partir da sua pasta de documentação:
module.exports = { myAutogeneratedSidebar: [ { type: 'autogenerated', dirName: '.', // '.' means the current docs folder }, ],};
Você também pode usar vários itens
gerados automaticamente em uma barra lateral, e entrelaçá-los com itens da barra lateral regular:
module.exports = { mySidebar: [ 'intro', { type: 'category', label: 'Tutorials', items: [ 'tutorial-intro', { type: 'autogenerated', dirName: 'tutorials/easy', // Generate sidebar slice from docs/tutorials/easy }, 'tutorial-medium', { type: 'autogenerated', dirName: 'tutorials/advanced', // Generate sidebar slice from docs/tutorials/hard }, 'tutorial-end', ], }, { type: 'autogenerated', dirName: 'guides', // Generate sidebar slice from docs/guides }, { type: 'category', label: 'Community', items: ['team', 'chat'], }, ],};
#
Metadados da barra lateral gerados automaticamentePor padrão, a fatia da barra lateral será gerada em ordem alfabética (usando arquivos e nomes de pastas).
Se a barra lateral gerada não parecer boa, você pode atribuir metadados adicionais a documentos e categorias.
Para documentos: use outros frontmatter:
---sidebar_label: Easysidebar_position: 2---
# Easy Tutorial
This is the easy tutorial!
Para categorias: adicione um arquivo _category_.json
ou _category_.yml
na pasta apropriada:
{ "label": "Tutorial", "position": 3}
label: 'Tutorial'position: 2.5 # posição flutuante é suportadacollapsible: true # tornar a categoria recolhívelcollapsed: false # mantenha a categoria aberta por padrão
info
Os metadados de posição são usados apenas dentro de uma fatia da barra lateral: o Docusaurus não reordena outros itens da sua barra lateral.
#
Usando prefixos numéricosUma maneira simples de ordenar uma barra lateral gerada automaticamente é prefixar arquivos e documentos por prefixos numéricos:
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
Para torná-lo mais fácil de adotar, o Docusaurus oferece suporte a vários padrões de prefixo de número.
Por padrão, o Docusaurus removerá o prefixo do id do documento, título, label e caminhos de URL.
caution
Prefira usar metadados adicionais.
Atualizar um prefixo de número pode ser irritante, pois pode exigir a atualização de vários links de marcação existentes:
- Verifique o [fim de tutorial](../04-End.md);+ Verifique o [fim de tutorial](../05-End.md);
#
Personalizar o gerador de itens da barra lateralVocê pode fornecer uma função personalizada de sidebarItemsGenerator
na configuração do plugin da documentação (ou predefinição):
module.exports = { plugins: [ [ '@docusaurus/plugin-content-docs', { sidebarItemsGenerator: async function ({ defaultSidebarItemsGenerator, numberPrefixParser, item, version, docs, }) { // Example: return an hardcoded list of static sidebar items return [ {type: 'doc', id: 'doc1'}, {type: 'doc', id: 'doc2'}, ]; }, }, ], ],};
tip
Reutilizar e aprimorar o gerador padrão em vez de escrever um gerador do zero.
Adicione, atualize, filtre os itens da barra lateral de acordo com seu caso de uso:
// 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', { sidebarItemsGenerator: async function ({ defaultSidebarItemsGenerator, ...args }) { const sidebarItems = await defaultSidebarItemsGenerator(args); return reverseSidebarItems(sidebarItems); }, }, ], ],};
#
Barra lateral ocultávelUsando a opção themeConfig.hideableSidebar
habilitada, você pode ocultar toda a barra lateral, permitindo que você concentre melhor seus usuários no conteúdo. Isso é especialmente útil quando o consumo de conteúdo em telas médias (por exemplo, em tablets).
module.exports = { themeConfig: { hideableSidebar: true, },};
#
Passando propriedades personalizadasPara passar props personalizados para um item da barra lateral alternada, adicione o objeto customProps
opcional a qualquer um dos itens:
{ type: 'doc', id: 'doc1', customProps: { /* props */ }}
#
Exemplo de barras laterais complexasExemplo do mundo real no site Docusaurus:
module.exports = { docs: [ 'introduction', { type: 'category', label: 'Getting Started', collapsed: false, items: [ 'installation', 'configuration', 'playground', 'typescript-support', ], }, { type: 'category', label: 'Guides', items: [ 'guides/creating-pages', { Docs: [ 'guides/docs/introduction', 'guides/docs/create-doc', 'guides/docs/sidebar', 'guides/docs/versioning', 'guides/docs/markdown-features', 'guides/docs/multi-instance', ], }, 'blog', { type: 'category', label: 'Markdown Features', items: [ 'guides/markdown-features/introduction', 'guides/markdown-features/react', 'guides/markdown-features/tabs', 'guides/markdown-features/code-blocks', 'guides/markdown-features/admonitions', 'guides/markdown-features/headings', 'guides/markdown-features/inline-toc', 'guides/markdown-features/assets', 'guides/markdown-features/plugins', 'guides/markdown-features/math-equations', 'guides/markdown-features/head-metadatas', ], }, 'styling-layout', 'static-assets', 'search', 'browser-support', 'deployment', { type: 'category', label: 'Internationalization', items: [ { type: 'doc', id: 'i18n/introduction', label: 'Introduction', }, { type: 'doc', id: 'i18n/tutorial', label: 'Tutorial', }, { type: 'doc', id: 'i18n/git', label: 'Using Git', }, { type: 'doc', id: 'i18n/crowdin', label: 'Using Crowdin', }, ], }, ], }, { type: 'category', label: 'Advanced Guides', items: ['using-plugins', 'using-themes', 'presets'], }, { type: 'category', label: 'Migrating from v1 to v2', items: [ 'migration/migration-overview', 'migration/migration-automated', 'migration/migration-manual', 'migration/migration-versioned-sites', 'migration/migration-translated-sites', ], }, ], api: [ 'cli', 'docusaurus-core', 'api/docusaurus.config.js', 'lifecycle-apis', { type: 'category', label: 'Plugins', items: [ 'api/plugins/plugins-overview', 'api/plugins/plugin-content-docs', 'api/plugins/plugin-content-blog', 'api/plugins/plugin-content-pages', 'api/plugins/plugin-client-redirects', 'api/plugins/plugin-debug', 'api/plugins/plugin-google-analytics', 'api/plugins/plugin-google-gtag', 'api/plugins/plugin-ideal-image', 'api/plugins/plugin-pwa', 'api/plugins/plugin-sitemap', ], }, { type: 'category', label: 'Themes', items: [ 'api/themes/themes-overview', 'api/themes/theme-configuration', 'api/themes/theme-classic', 'api/themes/theme-bootstrap', 'api/themes/theme-live-codeblock', 'api/themes/theme-search-algolia', ], }, ],};