Ir para o conteúdo principal
Version: 2.0.1

Blog

O recurso de blog permite que você importe rapidamente um blog com todas as funcionalidades.

info

Check the Blog Plugin API Reference documentation for an exhaustive list of options.

Configuração inicial

Para configurar o blog do seu site, comece criando um diretório blog.

Em seguida, adicione um link do item ao seu blog dentro de docusaurus.config.js:

docusaurus.config.js
module.exports = {
themeConfig: {
// ...
navbar: {
items: [
// ...
{to: 'blog', label: 'Blog', position: 'left'}, // ou position: 'right'
],
},
},
};

Adicionando posts

Para publicar no blog, crie um arquivo Markdown dentro do diretório do blog.

Por exemplo, crie um arquivo no website/blog/2019-09-05-hello-docusaurus-v2.md:

website/blog/2019-09-05-hello-docusaurus-v2.md
---
title: Welcome Docusaurus v2
description: This is my first post on Docusaurus 2.
slug: welcome-docusaurus-v2
authors:
- name: Joel Marcey
title: Co-creator of Docusaurus 1
url: https://github.com/JoelMarcey
image_url: https://github.com/JoelMarcey.png
- name: Sébastien Lorber
title: Docusaurus maintainer
url: https://sebastienlorber.com
image_url: https://github.com/slorber.png
tags: [hello, docusaurus-v2]
image: https://i.imgur.com/mErPwqL.png
hide_table_of_contents: false
---

Welcome to this blog. Esse blog foi criado com [**Docusaurus 2**](https://docusaurus.io/).

<!--truncate-->

This is my first post on Docusaurus 2.

Um monte de exploração para seguir.

A front matter é útil para adicionar mais metadados ao seu post de blog, por exemplo, informações de autor, mas o Docusaurus será capaz de inferir todos os metadados necessários sem o front matter. For all possible fields, see the API documentation.

Lista de Blog

A página de índice do blog (por padrão, está em /blog) é a blog list page, onde todas as postagens são exibidas coletivamente.

Use the <!--truncate--> marker in your blog post to represent what will be shown as the summary when viewing all published blog posts. Anything above <!--truncate--> will be part of the summary. Por exemplo:

---
title: Truncation Example
---

All these will be part of the blog post summary.

Até isso.

<!--truncate-->

But anything from here on down will not be.

Isso não.

Nem isso.

Por padrão, 10 postagens são mostradas em cada página na lista do blog, mas você pode controlar a paginação com a opção postsPerPage na configuração do plugin. Se você definir postsPerPage: 'ALL', a paginação será desativada e todas as postagens serão exibidas na primeira página. You can also add a meta description to the blog list page for better SEO:

docusaurus.config.js
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
blogTitle: 'Docusaurus blog!',
blogDescription: 'A Docusaurus powered blog!',
postsPerPage: 'ALL',
},
},
],
],
};

Barra lateral do blog

A barra lateral exibe os posts mais recentes do blog. O número padrão de itens exibidos é 5, mas você pode personalizar com a opção blogSidebarCount na configuração do plugin. Definindo blogSidebarCount: 0, a barra lateral será completamente desativada, com o contêiner removido também. Isso irá aumentar a largura do contêiner principal. Especialmente, se você definiu blogSidebarCount: 'ALL', todas as postagens serão exibidas.

Você também pode alterar o texto do cabeçalho da barra lateral com a opção blogSidebarTitle. For example, if you have set blogSidebarCount: 'ALL', instead of the default "Recent posts", you may rather make it say "All posts":

docusaurus.config.js
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
blogSidebarTitle: 'All posts',
blogSidebarCount: 'ALL',
},
},
],
],
};

Blog post date

O Docusaurus irá extrair uma data YYYY-MM-DD de um nome de arquivo/pasta, como YYYY-MM-DD-my-blog-post-title.md.

Exemplo de padrões suportados
PatternExemplo
Single file2021-05-28-meu-blog-post-title.md
MDX file2021-05-28-my-blog-post-title.mdx
Single folder + index.md2021-05-28-my-blog-post-title/index.md
Folder named by date2021-05-28/my-blog-post-title.md
Nested folders by date2021/05/28/my-blog-post-title.md
Partially nested folders by date2021/05-28-my-blog-post-title.md
Nested folders + index.md2021/05/28/my-blog-post-title/index.md
Date in the middle of pathcategory/2021/05-28-my-blog-post-title.md

The date will be excised from the path and appended to the beginning of the URL slug.

tip

Usar uma pasta pode ser conveniente para co-localizar imagens de publicação do blog juntamente com o arquivo Markdown.

This naming convention is optional, and you can also provide the date as front matter. Since the front matter follows YAML syntax where the datetime notation is supported, you can use front matter if you need more fine-grained publish dates. For example, if you have multiple posts published on the same day, you can order them according to the time of the day:

earlier-post.md
---
date: 2021-09-13T10:00
---
later-post.md
---
date: 2021-09-13T18:00
---

Blog post authors

Use the authors front matter field to declare blog post authors. An author should have at least a name or an image_url. Docusaurus uses information like url, email, and title, but any other information is allowed.

Inline authors

Blog post authors can be declared directly inside the front matter:

my-blog-post.md
---
authors:
name: Joel Marcey
title: Co-creator of Docusaurus 1
url: https://github.com/JoelMarcey
image_url: https://github.com/JoelMarcey.png
email: [email protected]
---
tip

This option works best to get started, or for casual, irregular authors.

info

Prefer using the authors front matter, but the legacy author_* front matter remains supported:

my-blog-post.md
---
author: Joel Marcey
author_title: Co-creator of Docusaurus 1
author_url: https://github.com/JoelMarcey
author_image_url: https://github.com/JoelMarcey.png
---

Global authors

For regular blog post authors, it can be tedious to maintain authors' information inlined in each blog post.

It is possible to declare those authors globally in a configuration file:

website/blog/authors.yml
jmarcey:
name: Joel Marcey
title: Co-creator of Docusaurus 1
url: https://github.com/JoelMarcey
image_url: https://github.com/JoelMarcey.png
email: [email protected]

slorber:
name: Sébastien Lorber
title: Docusaurus maintainer
url: https://sebastienlorber.com
image_url: https://github.com/slorber.png
tip

Use the authorsMapPath plugin option to configure the path. JSON is also supported.

In blog posts front matter, you can reference the authors declared in the global configuration file:

my-blog-post.md
---
authors: jmarcey
---
info

The authors system is very flexible and can suit more advanced use-case:

Mix inline authors and global authors

You can use global authors most of the time, and still use inline authors:

my-blog-post.md
---
authors:
- jmarcey
- slorber
- name: Inline Author name
title: Inline Author Title
url: https://github.com/inlineAuthor
image_url: https://github.com/inlineAuthor
---
Local override of global authors

You can customize the global author's data on per-blog-post basis:

my-blog-post.md
---
authors:
- key: jmarcey
title: Joel Marcey's new title
- key: slorber
name: Sébastien Lorber's new name
---
Localize the author's configuration file

The configuration file can be localized, just create a localized copy of it at:

website/i18n/[locale]/docusaurus-plugin-content-blog/authors.yml

An author, either declared through front matter or through the authors map, needs to have a name or an avatar, or both. If all authors of a post don't have names, Docusaurus will display their avatars compactly. See this test post for the effect.

Feed generation

RSS feeds require the author's email to be set for the author to appear in the feed.

Reading time

Docusaurus generates a reading time estimation for each blog post based on word count. We provide an option to customize this.

docusaurus.config.js
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
showReadingTime: true, // When set to false, the "x min read" won't be shown
readingTime: ({content, frontMatter, defaultReadingTime}) =>
defaultReadingTime({content, options: {wordsPerMinute: 300}}),
},
},
],
],
};

The readingTime callback receives three parameters: the blog content text as a string, front matter as a record of string keys and their values, and the default reading time function. It returns a number (reading time in minutes) or undefined (disable reading time for this page).

The default reading time is able to accept additional options: wordsPerMinute as a number (default: 300), and wordBound as a function from string to boolean. If the string passed to wordBound should be a word bound (spaces, tabs, and line breaks by default), the function should return true.

tip

Use the callback for all your customization needs:

Disable reading time on one page:

docusaurus.config.js
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
showReadingTime: true,
readingTime: ({content, frontMatter, defaultReadingTime}) =>
frontMatter.hide_reading_time
? undefined
: defaultReadingTime({content}),
},
},
],
],
};

Usage:

---
hide_reading_time: true
---

This page will no longer display the reading time stats!

Feed

You can generate RSS / Atom / JSON feed by passing feedOptions. Por padrão, os feeds RSS e Atom são gerados. Para desativar a geração de feed, defina feedOptions.type para null.

type FeedType = 'rss' | 'atom' | 'json';

type BlogOptions = {
feedOptions?: {
type?: FeedType | 'all' | FeedType[] | null;
title?: string;
description?: string;
copyright: string;
language?: string; // possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
};
};

Exemplo de Uso:

docusaurus.config.js
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
feedOptions: {
type: 'all',
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`,
},
},
},
],
],
};

The feeds can be found at:

https://example.com/blog/rss.xml

Tópicos avançados

Modo somente blog

You can run your Docusaurus 2 site without a dedicated landing page and instead have your blog's post list page as the index page. Set the routeBasePath to be '/' to serve the blog through the root route example.com/ instead of the subroute example.com/blog/.

docusaurus.config.js
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: false, // Optional: disable the docs plugin
blog: {
routeBasePath: '/', // Serve the blog at the site's root
/* other blog options */
},
},
],
],
};
caution

Não se esqueça de excluir a página inicial existente em ./src/pages/index.js ou então haverá dois arquivos mapeados para a mesma rota!

tip

There's also a "Docs-only mode" for those who only want to use the docs. Read Docs-only mode for detailed instructions or a more elaborate explanation of routeBasePath.

Vários blogs

Por padrão, o tema clássico pressupõe apenas um blog por site e, portanto, inclui apenas uma instância do plugin do blog. Se você gostaria de ter vários blogs em um único site, também é possível! Você pode adicionar outro blog, especificando outro plugin no plugin opção para docusaurus.config.js.

Defina o routeBasePath para a rota de URL na qual você deseja que seu segundo blog seja acessado. Observe que o routeBasePath aqui deve ser diferente do primeiro blog ou pode haver uma colisão entre itens! Além disso, defina o caminho para o diretório que contém as entradas do seu segundo blog.

As documented for multi-instance plugins, you need to assign a unique ID to the plugins.

docusaurus.config.js
module.exports = {
// ...
plugins: [
[
'@docusaurus/plugin-content-blog',
{
/**
* Obrigatório para qualquer plugin multi-instância
*/
id: 'second-blog',
/**
* Rota de URL para a seção do blog do seu site.
* * NÃO * inclua uma barra final.
*/
routeBasePath: 'my-second-blog',
/**
* Caminho para os dados no sistema de arquivos relativo ao diretório do site.
*/
path: './my-second-blog',
},
],
],
};

Como exemplo, nós hospedamos um segundo blog aqui.