Configuração do tema
Esta configuração se aplica a todos os temas principais.
#
Comum#
Color modeO tema clássico fornece, por padrão, suporte ao modo claro e escuro, com um botão de navegação para o usuário.
It is possible to customize the color mode support within the colorMode
object.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
defaultMode | !!crwdBlockTags_255_sgaTkcolBdwrc!! | 'light' | The color mode when user first visits the site. |
disableSwitch | boolean | false | Hides the switch in the navbar. Useful if you want to support a single color mode. |
respectPrefersColorScheme | boolean | false | Whether to use the prefers-color-scheme media-query, using user system preferences, instead of the hardcoded defaultMode . |
switchConfig | See below | See below | Dark/light switch icon options. |
switchConfig.darkIcon | string | '🌜' | Icon for the switch while in dark mode. |
switchConfig.darkIconStyle | JSX style object (see documentation) | {} | CSS to apply to dark icon. |
switchConfig.lightIcon | string | '🌞' | Icon for the switch while in light mode. |
switchConfig.lightIconStyle | JSX style object | {} | CSS to apply to light icon. |
Configuração de exemplo:
module.exports = { themeConfig: { colorMode: { defaultMode: 'light', disableSwitch: false, respectPrefersColorScheme: false, switchConfig: { darkIcon: '🌙', darkIconStyle: { marginLeft: '2px', }, // Unicode icons such as '\u2600' will work // Unicode with 5 chars require brackets: '\u{1F602}' lightIcon: '\u{1F602}', lightIconStyle: { marginLeft: '1px', }, }, }, },};
caution
Com respectPrefersColorScheme: true
, o defaultMode
é substituído pelas preferências do sistema do usuário.
Se você deseja oferecer suporte a apenas um modo de cor, provavelmente deseja ignorar as preferências do sistema do usuário.
#
Meta imagemVocê pode configurar uma imagem padrão que será usada para sua meta tag, em particular og:image
e twitter:image
.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
image | string | undefined | The meta image URL for the site. Relative to your site's "static" directory. Cannot be SVGs. Também podem ser URLs externos. |
Configuração de exemplo:
module.exports = { themeConfig: { image: 'img/docusaurus.png', },};
#
MetadadosVocê pode configurar metadados html adicionais (e substituir os existentes).
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
metadatas | Metadata[] | [] | Any field will be directly passed to the <meta /> tag. Possible fields include id , name , property , content , itemprop , etc. |
Configuração de exemplo:
module.exports = { themeConfig: { metadatas: [{name: 'twitter:card', content: 'summary'}], },};
#
Barra de AnúnciosÀs vezes, você deseja anunciar algo em seu site. Apenas para esse caso, você pode adicionar uma barra de anúncios. Este é um painel não fixo e opcionalmente descartável acima da barra de navegação. All configuration are in the announcementBar
object.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
id | string | 'announcement-bar' | Any value that will identify this message. |
content | string | '' | The text content of the announcement. HTML will be interpolated. |
backgroundColor | string | '#fff' | Background color of the entire bar. |
textColor | string | '#000' | Announcement text color. |
isCloseable | boolean | true | Whether this announcement can be dismissed with a '×' button. |
Configuração de exemplo:
module.exports = { themeConfig: { announcementBar: { id: 'support_us', content: 'We are looking to revamp our docs, please fill <a target="_blank" rel="noopener noreferrer" href="#">this survey</a>', backgroundColor: '#fafbfc', textColor: '#091E42', isCloseable: false, }, },};
#
Barra de navegaçãoCampos aceitos:
Name | Type | Default | Description |
---|---|---|---|
title | string | undefined | Title for the navbar. |
logo | See below | undefined | Customization of the logo object. |
items | NavbarItem[] | [] | A list of navbar items. See specification below. |
hideOnScroll | boolean | false | Whether the navbar is hidden when the user scrolls down. |
style | !!crwdBlockTags_299_sgaTkcolBdwrc!! | Same as theme | Sets the navbar style, ignoring the dark/light theme. |
#
Navbar logoThe logo can be placed in static folder. O URL do logotipo é definido como base para o URL do seu site por padrão. Embora você possa especificar sua própria URL para o logotipo, se for um link externo, ele será aberto em uma nova guia. Além disso, você pode substituir um valor para o atributo alvo do link do logotipo, ele pode ser útil se você estiver hospedando documentos em um subdiretório do seu site principal, e nesse caso você provavelmente não precisa de um link no logotipo para o site principal será aberto em uma nova guia.
Para melhorar o suporte ao modo escuro, você também pode definir um logotipo diferente para este modo.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
alt | string | undefined | Alt tag for the logo image. |
src | string | Required | URL to the logo image. Base URL is appended by default. |
srcDark | string | logo.src | An alternative image URL to use in dark mode. |
href | string | siteConfig.baseUrl | Link to navigate to when the logo is clicked. |
target | string | Calculated based on href (external links will open in a new tab, all others in the current one). | The target attribute of the link; controls whether the link is opened in a new tab, the current one, or otherwise. |
Configuração de exemplo:
module.exports = { themeConfig: { navbar: { title: 'Site Title', logo: { alt: 'Site Logo', src: 'img/logo.svg', srcDark: 'img/logo_dark.svg', href: 'https://docusaurus.io/', target: '_self', }, }, },};
#
Itens da barra de navegaçãoVocê pode adicionar itens à barra de navegação por meio de themeConfig.navbar.items
.
module.exports = { themeConfig: { navbar: { items: [ { type: 'doc', position: 'left', docId: 'introduction', label: 'Docs', }, {to: 'blog', label: 'Blog', position: 'left'}, { type: 'docsVersionDropdown', position: 'right', }, { type: 'localeDropdown', position: 'right', }, { href: 'https://github.com/facebook/docusaurus', position: 'right', className: 'header-github-link', 'aria-label': 'GitHub repository', }, ], }, },};
Os itens podem ter comportamentos diferentes com base no campo type
. As seções a seguir apresentarão a você todos os tipos de itens disponíveis na barra de navegação.
#
Link da barra de navegaçãoPor padrão, os itens da barra de navegação são links regulares (interno ou externo).
O React Router deve aplicar automaticamente o estilo do link ativo aos links, mas você pode usar activeBasePath
em casos extremos. Para casos em que um link deve estar ativo em vários caminhos diferentes (como quando você tem várias pastas de documentos na mesma barra lateral), você pode usar activeBaseRegex
. activeBaseRegex
é uma alternativa mais flexível para activeBasePath
e tem precedência sobre ele -- o Docusaurus analisa em uma expressão regular que é testada contra a URL atual.
Os links externos (externos) obtêm atributos target="_blank" rel="noopener noreferrer"
automaticamente.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
label | string | Required | The name to be shown for this item. |
to | string | Required | Client-side routing, used for navigating within the website. O baseUrl será adicionado automaticamente a este valor. |
href | string | Required | A full-page navigation, used for navigating outside of the website. Only one of to or href should be used. |
prependBaseUrlToHref | boolean | false | Prepends the baseUrl to href values. |
position | !!crwdBlockTags_342_sgaTkcolBdwrc!! | 'left' | The side of the navbar this item should appear on. |
activeBasePath | string | to / href | To apply the active class styling on all routes starting with this path. Isto geralmente não é necessário. |
activeBaseRegex | string | undefined | Alternative to activeBasePath if required. |
className | string | '' | Custom CSS class (for styling any item). |
Configuração de exemplo:
module.exports = { themeConfig: { navbar: { items: [ { to: 'docs/introduction', // Apenas um "to" ou "href" deve ser usado // href: 'https://www.facebook.com', label: 'Introduction', position: 'left', activeBaseRegex: 'docs/(next|v8)', }, ], }, },};
#
Lista suspensa da barra de navegaçãoOs itens da barra de navegação do tipo dropdown
têm o campo itens
adicional, uma matriz interna de itens da barra de navegação.
Itens suspensos da barra de navegação só aceitam os seguintes tipos de itens "link-like":
Note que o item de base suspenso também é um link clicável para que este item possa receber qualquer uma das propriedades de um link simples da barra de navegação.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
label | string | Required | The name to be shown for this item. |
items | !!crwdBlockTags_349_sgaTkcolBdwrc!! | Required | The items to be contained in the dropdown. |
position | !!crwdBlockTags_350_sgaTkcolBdwrc!! | 'left' | The side of the navbar this item should appear on. |
Configuração de exemplo:
module.exports = { themeConfig: { navbar: { items: [ { type: 'dropdown', label: 'Community', position: 'left', items: [ { label: 'Facebook', href: 'https://www.facebook.com', }, { type: 'doc', label: 'Social', docId: 'social', }, // ... more items ], }, ], }, },};
#
Link de doc na barra de navegaçãoSe você deseja vincular a uma documentação específica, esse tipo especial de item da barra de navegação irá renderizar o link para o documento do docId
fornecido. Ele obterá a classe navbar__link--active
contanto que você navegue em um documento da mesma barra lateral.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
docId | string | Required | The ID of the doc that this item links to. |
label | string | docId | The name to be shown for this item. |
position | !!crwdBlockTags_362_sgaTkcolBdwrc!! | 'left' | The side of the navbar this item should appear on. |
docsPluginId | string | 'default' | The ID of the docs plugin that the doc belongs to. |
Configuração de exemplo:
módulo xports = { themeConfig: { navbar: { items: [ { type: 'doc', posição: 'esquerda', docId: 'Introdução', rótulo: 'Documentos', }, // realçar-fim ], }, },};
#
Lista suspensa de versões de documentos da NavbarSe você usa documentos com versões, este tipo de item especial da barra de navegação que irá exibir todas as versões disponíveis do seu site.
O usuário poderá mudar de uma versão para outra enquanto ficar no mesmo documento (desde que o id do documento seja constante entre versões).
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
position | !!crwdBlockTags_376_sgaTkcolBdwrc!! | 'left' | The side of the navbar this item should appear on. |
dropdownItemsBefore | !!crwdBlockTags_377_sgaTkcolBdwrc!! | [] | Add additional dropdown items at the beginning of the dropdown. |
dropdownItemsAfter | !!crwdBlockTags_378_sgaTkcolBdwrc!! | [] | Add additional dropdown items at the end of the dropdown. |
docsPluginId | string | 'default' | The ID of the docs plugin that the doc versioning belongs to. |
dropdownActiveClassDisabled | boolean | false | Do not add the link active class when browsing docs. |
Configuração de exemplo:
module.exports = { themeConfig: { navbar: { items: [ { type: 'docsVersionDropdown', position: 'left', dropdownItemsAfter: [{to: '/versions', label: 'All versions'}], dropdownActiveClassDisabled: true, }, ], }, },};
#
Versão dos docs da NavbarSe você usar documentos com versão, esse tipo de item especial da barra de navegação irá vincular com a versão ativa/navegada do seu documento (depende da URL atual), e voltar para a versão mais recente.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
label | string | The active/latest version label. | The name to be shown for this item. |
to | string | The active/latest version. | The internal link that this item points to. |
position | !!crwdBlockTags_389_sgaTkcolBdwrc!! | 'left' | The side of the navbar this item should appear on. |
docsPluginId | string | 'default' | The ID of the docs plugin that the doc versioning belongs to. |
Configuração de exemplo:
module.exports = { themeConfig: { navbar: { items: [ { type: 'docsVersion', position: 'left', to: '/path', label: 'label', }, ], }, },};
#
Menu suspenso de localidade da NavbarSe você usar o i18n feature, este tipo de item especial da barra de navegação irá renderizar um menu suspenso com todas as localidades disponíveis do seu site.
O usuário poderá mudar de uma localidade para outra, enquanto permanece na mesma página.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
position | !!crwdBlockTags_397_sgaTkcolBdwrc!! | 'left' | The side of the navbar this item should appear on. |
dropdownItemsBefore | !!crwdBlockTags_398_sgaTkcolBdwrc!! | [] | Add additional dropdown items at the beginning of the dropdown. |
dropdownItemsAfter | !!crwdBlockTags_399_sgaTkcolBdwrc!! | [] | Add additional dropdown items at the end of the dropdown. |
Configuração de exemplo:
module.exports = { themeConfig: { navbar: { items: [ { type: 'localeDropdown', position: 'left', dropdownItemsAfter: [ { to: 'https://my-site.com/help-us-translate', label: 'Help us translate', }, ], }, ], }, },};
#
Pesquisa na NavbarSe você usar a pesquisa, a barra de pesquisa será o elemento mais à direita na barra de navegação.
No entanto, com este tipo de item especial da barra de navegação, você pode mudar o local padrão.
Name | Type | Default | Description |
---|---|---|---|
position | !!crwdBlockTags_403_sgaTkcolBdwrc!! | 'left' | The side of the navbar this item should appear on. |
module.exports = { themeConfig: { navbar: { items: [ { type: 'search', position: 'right', }, ], }, },};
#
Auto-ocultar a barra de navegaçãoVocê pode ativar esta interface de usuário legal que automaticamente oculta a barra de navegação quando um usuário começa a rolar para baixo a página, e mostrar novamente quando o usuário rola para cima.
module.exports = { themeConfig: { navbar: { hideOnScroll: true, }, },};
#
Estilo barra de navegaçãoVocê pode definir o estilo estático da barra de navegação sem desativar a habilidade de mudar de tema. O estilo selecionado sempre será aplicado, não importa qual usuário de tema tenha selecionado.
Atualmente, existem duas possíveis opções de estilo: dark
e primary
(baseado na cor --ifm-color-primary
). Você pode ver a pré-visualização de estilos na documentação da Infima.
module.exports = { themeConfig: { navbar: { style: 'primary', }, },};
#
CodeBlockO Docusaurus usa Prism React Renderer para destacar blocos de código. All configuration are in the prism
object.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
theme | PrismTheme | palenight | The Prism theme to use for light-theme code blocks. |
darkTheme | PrismTheme | palenight | The Prism theme to use for dark-theme code blocks. |
defaultLanguage | string | undefined | The side of the navbar this item should appear on. |
#
TemaPor padrão, usamos Palenight como tema de destaque de sintaxe. É possível especificar um tema personalizado da lista de temas disponíveis. You may also use a different syntax highlighting theme when the site is in dark mode.
Configuração de exemplo:
module.exports = { themeConfig: { prism: { theme: require('prism-react-renderer/themes/github'), darkTheme: require('prism-react-renderer/themes/dracula'), }, },};
note
Se você usar a linha que destaca a sintaxe Markdown, talvez seja necessário especificar uma cor de destaque diferente para o tema de destaque do modo escuro. Consulte a documentação para obter orientação.
#
Idioma padrãoVocê pode definir uma linguagem padrão para blocos de código se nenhuma língua for adicionada após a tripla quantidade de backticks de abertura (ou seja, ```). Note that a valid language name must be passed.
Configuração de exemplo:
module.exports = { themeConfig: { prism: { defaultLanguage: 'javascript', }, },};
#
RodapéPode adicionar o logotipo e um direito autoral ao rodapé através do themeConfig.footer
. O logotipo pode ser colocado na pasta estática. A URL do logotipo funciona da mesma maneira do logotipo da barra de navegação.
Campos aceitos:
Name | Type | Default | Description |
---|---|---|---|
logo | Logo | undefined | Customization of the logo object. See Navbar logo for details. |
copyright | string | undefined | The copyright message to be displayed at the bottom. |
style | !!crwdBlockTags_426_sgaTkcolBdwrc!! | 'light' | The color theme of the footer component. |
items | FooterItem[] | [] | The link groups to be present. |
Configuração de exemplo:
module.exports = { themeConfig: { footer: { logo: { alt: 'Facebook Open Source Logo', src: 'img/oss_logo.png', href: 'https://opensource.facebook.com', }, copyright: `Copyright © ${new Date().getFullYear()} My Project, Inc. Built with Docusaurus.`, }, },};
#
Links do rodapéYou can add links to the footer via themeConfig.footer.links
.
Accepted fields of each link section:
Name | Type | Default | Description |
---|---|---|---|
title | string | undefined | Label of the section of these links. |
items | FooterLink[] | [] | Links in this section. |
Accepted fields of each item in items
:
Name | Type | Default | Description |
---|---|---|---|
label | string | Required | Text to be displayed for this link. |
to | string | Required | Client-side routing, used for navigating within the website. O baseUrl será adicionado automaticamente a este valor. |
href | string | Required | A full-page navigation, used for navigating outside of the website. Only one of to or href should be used. |
html | string | undefined | Renders the html pass-through instead of a simple link. In case html is used, no other options should be provided. |
Configuração de exemplo:
module.exports = { footer: { links: [ { title: 'Docs', items: [ { label: 'Style Guide', to: 'docs/', }, { label: 'Second Doc', to: 'docs/doc2/', }, ], }, { title: 'Community', items: [ { label: 'Stack Overflow', href: 'https://stackoverflow.com/questions/tagged/docusaurus', }, { label: 'Discord', href: 'https://discordapp.com/invite/docusaurus', }, { label: 'Twitter', href: 'https://twitter.com/docusaurus', }, { html: ` <a href="https://www.netlify.com" target="_blank" rel="noreferrer noopener" aria-label="Deploys by Netlify"> <img src="https://www.netlify.com/img/global/badges/netlify-color-accent.svg" alt="Deploys by Netlify" /> </a> `, }, ], }, ], },};
#
GanchosuseThemeContext
#
React hook para acessar o contexto do tema. Este contexto contém funções para definir o modo claro e escuro e expõe a variável booleana, indicando qual modo está em uso no momento.
Exemplo de uso:
import React from 'react';import useThemeContext from '@theme/hooks/useThemeContext';
const Example = () => { const {isDarkTheme, setLightTheme, setDarkTheme} = useThemeContext();
retornar <h1>Modo escuro agora é {isDarkTheme ? 'on' : 'off'}</h1>;};
note
O componente que chama useThemeContext
deve ser filho do componente Layout
.
function ExamplePage() { return ( <Layout> <Example /> </Layout> );}
#
i18nLeia a introdução i18n primeiro.
#
Localização dos arquivos de tradução- Caminho base:
website/i18n/<locale>/docusaurus-theme-<themeName>
- Caminho de multi-instância: N/A
- Arquivos JSON: extraídos com
docusaurus escreveu-traduções
- Arquivos Markdown: N/A
#
Exemplo de estrutura de sistema de arquivoswebsite/i18n/<locale>/docusaurus-theme-classic├├# traduções para o tema── navbar.json── footer.json