Aller au contenu principal
Version : 2.4.0

Blog

La fonction blog vous permet de déployer un blog complet en un rien de temps.

info

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

Initial setup

To set up your site's blog, start by creating a blog directory.

Then, add an item link to your blog within docusaurus.config.js:

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

Adding posts

Pour publier dans le blog, créez un fichier Markdown dans le répertoire blog.

For example, create a file at 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. This blog is created with [**Docusaurus 2**](https://docusaurus.io/).

<!--truncate-->

This is my first post on Docusaurus 2.

A whole bunch of exploration to follow.

The front matter is useful to add more metadata to your blog post, for example, author information, but Docusaurus will be able to infer all necessary metadata without the front matter. For all possible fields, see the API documentation.

Blog list

The blog's index page (by default, it is at /blog) is the blog list page, where all blog posts are collectively displayed.

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. Par exemple :

---
title: Truncation Example
---

All these will be part of the blog post summary.

Even this.

<!--truncate-->

But anything from here on down will not be.

Not this.

Or this.

By default, 10 posts are shown on each blog list page, but you can control pagination with the postsPerPage option in the plugin configuration. If you set postsPerPage: 'ALL', pagination will be disabled and all posts will be displayed on the first page. Vous pouvez également ajouter une méta description à la page de la liste de blog pour un meilleur référencement :

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

Blog sidebar

La barre latérale du blog affiche les articles récents du blog. The default number of items shown is 5, but you can customize with the blogSidebarCount option in the plugin configuration. By setting blogSidebarCount: 0, the sidebar will be completely disabled, with the container removed as well. Cela augmentera la largeur du conteneur principal. Specially, if you have set blogSidebarCount: 'ALL', all posts will be displayed.

You can also alter the sidebar heading text with the blogSidebarTitle option. 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: 'Tous les articles',
blogSidebarCount: 'ALL',
},
},
],
],
};

Blog post date

Docusaurus will extract a YYYY-MM-DD date from a file/folder name such as YYYY-MM-DD-my-blog-post-title.md.

Example supported patterns
ModèleExemple
Fichier simple2021-05-28-my-blog-post-title.md
Fichier MDX2021-05-28-my-blog-post-title.mdx
Single folder + index.md2021-05-28-my-blog-post-title/index.md
Dossier nommé par date2021-05-28/my-blog-post-title.md
Dossiers imbriqués par date2021/05/28/my-blog-post-title.md
Dossiers partiellement imbriqués par date2021/05-28-my-blog-post-title.md
Nested folders + index.md2021/05/28/my-blog-post-title/index.md
Date au milieu du chemincategory/2021/05-28-my-blog-post-title.md

La date sera supprimée du chemin et ajoutée au début du slug de l'URL.

astuce

L'utilisation d'un dossier peut s'avérer pratique pour placer les images de l'article de blog au même endroit que le fichier Markdown.

Cette convention de nommage est facultative et vous pouvez fournir la date dans le frontmatter. Puisque le frontmatter suit la syntaxe YAML où la notation de la date est prise en charge, vous pouvez utiliser le frontmatter si vous avez besoin de dates de publication plus précises. Par exemple, si vous avez plusieurs messages publiés le même jour, vous pouvez les trier selon l'heure de la journée :

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

Les auteurs d'articles du blog peuvent être déclarés directement à l'intérieur du frontmatter :

my-blog-post.md
---
authors:
name: Joel Marcey
title: Co-créateur de Docusaurus 1
url: https://github.com/JoelMarcey
image_url: https://github.com/JoelMarcey.png
email: [email protected]
---
astuce

Cette option est la plus efficace pour débuter, ou pour les auteurs occasionnels et irréguliers.

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-créateur de Docusaurus 1
author_url: https://github.com/JoelMarcey
author_image_url: https://github.com/JoelMarcey.png
---

Global authors

Pour les auteurs réguliers du blog, il peut être fastidieux de maintenir les informations des auteurs dans chaque article du blog.

Il est possible de déclarer ces auteurs globalement dans un fichier de configuration :

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

slorber:
name: Sébastien Lorber
title: Mainteneur de Docusaurus
url: https://sebastienlorber.com
image_url: https://github.com/slorber.png
astuce

Use the authorsMapPath plugin option to configure the path. Le JSON est également pris en charge.

Dans le frontmatter des articles du blog, vous pouvez référencer les auteurs déclarés dans le fichier de configuration globale :

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

Vous pouvez utiliser les auteurs globaux la plupart du temps, et toujours utiliser les auteurs en ligne :

my-blog-post.md
---
authors:
- jmarcey
- slorber
- name: Nom de l'auteur en ligne
title: Titre de l'auteur en ligne
url: https://github.com/inlineAuthor
image_url: https://github.com/inlineAuthor
---
Local override of global authors

Vous pouvez personnaliser les données globales de l'auteur sur la base de chaque article du blog:

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

Le fichier de configuration peut être traduit, il suffit d'en créer une copie traduite à cet endroit :

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

Un auteur, qu'il soit déclaré par le front matter ou par la carte des auteurs, doit avoir un nom ou un avatar, ou les deux. Si tous les auteurs d'un message n'ont pas de noms, Docusaurus affichera leurs avatars de manière compacte. 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 génère une estimation du temps de lecture pour chaque article du blog basé sur le nombre de mots. Nous fournissons une option pour personnaliser cela.

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.

astuce

Utilisez le callback pour tous vos besoins de personnalisation :

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}),
},
},
],
],
};

Utilisation :

---
hide_reading_time: true
---

Cette page n'affichera plus les stats de temps de lecture !

Feed

You can generate RSS / Atom / JSON feed by passing feedOptions. Par défaut, les flux RSS et Atom sont générés. To disable feed generation, set feedOptions.type to 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
/** Allow control over the construction of BlogFeedItems */
createFeedItems?: (params: {
blogPosts: BlogPost[];
siteConfig: DocusaurusConfig;
outDir: string;
defaultCreateFeedItems: (params: {
blogPosts: BlogPost[];
siteConfig: DocusaurusConfig;
outDir: string;
}) => Promise<BlogFeedItem[]>;
}) => Promise<BlogFeedItem[]>;
};
};

Exemple d'utilisation:

docusaurus.config.js
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
feedOptions: {
type: 'all',
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`,
createFeedItems: async (params) => {
const {blogPosts, defaultCreateFeedItems, ...rest} = params;
return defaultCreateFeedItems({
// keep only the 10 most recent blog posts in the feed
blogPosts: blogPosts.filter((item, index) => index < 10),
...rest,
});
},
},
},
},
],
],
};

Le flux peut être trouvé sur :

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

Advanced topics

Blog-only mode

Vous pouvez faire fonctionner votre site Docusaurus 2 sans page d'accueil dédiée et utiliser la liste des articles de votre blog comme page d'index. 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 */
},
},
],
],
};
attention

Don't forget to delete the existing homepage at ./src/pages/index.js or else there will be two files mapping to the same route!

astuce

Il y a aussi un « mode Docs-uniquement » pour ceux qui ne veulent utiliser que les Docs. Read Docs-only mode for detailed instructions or a more elaborate explanation of routeBasePath.

Multiple blogs

Par défaut, le thème classic n'assume qu'un seul blog par site et n'inclut donc qu'une seule instance du plugin blog. Si vous souhaitez avoir plusieurs blogs sur un seul site web, c'est aussi possible ! You can add another blog by specifying another blog plugin in the plugins option for docusaurus.config.js.

Set the routeBasePath to the URL route that you want your second blog to be accessed on. Note that the routeBasePath here has to be different from the first blog or else there could be a collision of paths! Also, set path to the path to the directory containing your second blog's entries.

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',
{
/**
* Required for any multi-instance plugin
*/
id: 'second-blog',
/**
* URL route for the blog section of your site.
* *DO NOT* include a trailing slash.
*/
routeBasePath: 'my-second-blog',
/**
* Path to data on filesystem relative to site dir.
*/
path: './my-second-blog',
},
],
],
};

As an example, we host a second blog here.