chore: release Docusaurus v3.2.0 (#10000)

This commit is contained in:
Sébastien Lorber 2024-03-29 17:51:27 +01:00 committed by GitHub
parent 1a5fe5c412
commit debfc87d34
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
143 changed files with 21115 additions and 202 deletions

View file

@ -0,0 +1,5 @@
label: Plugins
position: 2
link:
type: doc
id: api/plugins/plugins-overview # Dogfood using a "qualified id"

View file

@ -0,0 +1,30 @@
---
sidebar_position: 0
id: plugins-overview
sidebar_label: Plugins overview
slug: /api/plugins
---
# Docusaurus plugins
We provide official Docusaurus plugins.
## Content plugins {#content-plugins}
These plugins are responsible for loading your site's content, and creating pages for your theme to render.
- [@docusaurus/plugin-content-docs](./plugin-content-docs.mdx)
- [@docusaurus/plugin-content-blog](./plugin-content-blog.mdx)
- [@docusaurus/plugin-content-pages](./plugin-content-pages.mdx)
## Behavior plugins {#behavior-plugins}
These plugins will add a useful behavior to your Docusaurus site.
- [@docusaurus/plugin-debug](./plugin-debug.mdx)
- [@docusaurus/plugin-sitemap](./plugin-sitemap.mdx)
- [@docusaurus/plugin-pwa](./plugin-pwa.mdx)
- [@docusaurus/plugin-client-redirects](./plugin-client-redirects.mdx)
- [@docusaurus/plugin-ideal-image](./plugin-ideal-image.mdx)
- [@docusaurus/plugin-google-analytics](./plugin-google-analytics.mdx)
- [@docusaurus/plugin-google-gtag](./plugin-google-gtag.mdx)

View file

@ -0,0 +1,127 @@
---
sidebar_position: 4
slug: /api/plugins/@docusaurus/plugin-client-redirects
---
# 📦 plugin-client-redirects
import APITable from '@site/src/components/APITable';
Docusaurus Plugin to generate **client-side redirects**.
This plugin will write additional HTML pages to your static site that redirect the user to your existing Docusaurus pages with JavaScript.
:::warning production only
This plugin is always inactive in development and **only active in production** because it works on the build output.
:::
:::warning
It is better to use server-side redirects whenever possible.
Before using this plugin, you should look if your hosting provider doesn't offer this feature.
:::
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-client-redirects
```
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `fromExtensions` | `string[]` | `[]` | The extensions to be removed from the route after redirecting. |
| `toExtensions` | `string[]` | `[]` | The extensions to be appended to the route after redirecting. |
| `redirects` | <code>[RedirectRule](#RedirectRule)[]</code> | `[]` | The list of redirect rules. |
| `createRedirects` | <code>[CreateRedirectsFn](#CreateRedirectsFn)</code> | `undefined` | A callback to create a redirect rule. Docusaurus query this callback against every path it has created, and use its return value to output more paths. |
```mdx-code-block
</APITable>
```
:::note
This plugin will also read the [`siteConfig.onDuplicateRoutes`](../docusaurus.config.js.mdx#onDuplicateRoutes) config to adjust its logging level when multiple files will be emitted to the same location.
:::
### Types {#types}
#### `RedirectRule` {#RedirectRule}
```ts
type RedirectRule = {
to: string;
from: string | string[];
};
```
:::note
The idea of "from" and "to" is central in this plugin. "From" means a path that you want to _create_, i.e. an extra HTML file that will be written; "to" means a path to want to redirect _to_, usually a route that Docusaurus already knows about.
This is why you can have multiple "from" for the same "to": we will create multiple HTML files that all redirect to the same destination. On the other hand, one "from" can never have more than one "to": the written HTML file needs to have a determinate destination.
:::
#### `CreateRedirectsFn` {#CreateRedirectsFn}
```ts
// The parameter `path` is a route that Docusaurus has already created. It can
// be seen as the "to", and your return value is the "from". Returning a falsy
// value will not create any redirect pages for this particular path.
type CreateRedirectsFn = (path: string) => string[] | string | null | undefined;
```
### Example configuration {#ex-config}
Here's an example configuration:
```js title="docusaurus.config.js"
export default {
plugins: [
[
'@docusaurus/plugin-client-redirects',
// highlight-start
{
fromExtensions: ['html', 'htm'], // /myPage.html -> /myPage
toExtensions: ['exe', 'zip'], // /myAsset -> /myAsset.zip (if latter exists)
redirects: [
// /docs/oldDoc -> /docs/newDoc
{
to: '/docs/newDoc',
from: '/docs/oldDoc',
},
// Redirect from multiple old paths to the new path
{
to: '/docs/newDoc2',
from: ['/docs/oldDocFrom2019', '/docs/legacyDocFrom2016'],
},
],
createRedirects(existingPath) {
if (existingPath.includes('/community')) {
// Redirect from /docs/team/X to /community/X and /docs/support/X to /community/X
return [
existingPath.replace('/community', '/docs/team'),
existingPath.replace('/community', '/docs/support'),
];
}
return undefined; // Return a falsy value: no redirect created
},
},
// highlight-end
],
],
};
```

View file

@ -0,0 +1,307 @@
---
sidebar_position: 2
slug: /api/plugins/@docusaurus/plugin-content-blog
---
# 📦 plugin-content-blog
import APITable from '@site/src/components/APITable';
Provides the [Blog](blog.mdx) feature and is the default blog plugin for Docusaurus.
:::warning some features production only
The [feed feature](../../blog.mdx#feed) works by extracting the build output, and is **only active in production**.
:::
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-content-blog
```
:::tip
If you use the preset `@docusaurus/preset-classic`, you don't need to install this plugin as a dependency.
You can configure this plugin through the [preset options](../../using-plugins.mdx#docusauruspreset-classic).
:::
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `path` | `string` | `'blog'` | Path to the blog content directory on the file system, relative to site dir. |
| `editUrl` | <code>string \| [EditUrlFn](#EditUrlFn)</code> | `undefined` | Base URL to edit your site. The final URL is computed by `editUrl + relativePostPath`. Using a function allows more nuanced control for each file. Omitting this variable entirely will disable edit links. |
| `editLocalizedFiles` | `boolean` | `false` | The edit URL will target the localized file, instead of the original unlocalized file. Ignored when `editUrl` is a function. |
| `blogTitle` | `string` | `'Blog'` | Blog page title for better SEO. |
| `blogDescription` | `string` | `'Blog'` | Blog page meta description for better SEO. |
| `blogSidebarCount` | <code>number \| 'ALL'</code> | `5` | Number of blog post elements to show in the blog sidebar. `'ALL'` to show all blog posts; `0` to disable. |
| `blogSidebarTitle` | `string` | `'Recent posts'` | Title of the blog sidebar. |
| `routeBasePath` | `string` | `'blog'` | URL route for the blog section of your site. **DO NOT** include a trailing slash. Use `/` to put the blog at root path. |
| `tagsBasePath` | `string` | `'tags'` | URL route for the tags section of your blog. Will be appended to `routeBasePath`. |
| `pageBasePath` | `string` | `'page'` | URL route for the pages section of your blog. Will be appended to `routeBasePath`. |
| `archiveBasePath` | <code>string \| null</code> | `'archive'` | URL route for the archive section of your blog. Will be appended to `routeBasePath`. **DO NOT** include a trailing slash. Use `null` to disable generation of archive. |
| `include` | `string[]` | `['**/*.{md,mdx}']` | Array of glob patterns matching Markdown files to be built, relative to the content path. |
| `exclude` | `string[]` | _See example configuration_ | Array of glob patterns matching Markdown files to be excluded. Serves as refinement based on the `include` option. |
| `postsPerPage` | <code>number \| 'ALL'</code> | `10` | Number of posts to show per page in the listing page. Use `'ALL'` to display all posts on one listing page. |
| `blogListComponent` | `string` | `'@theme/BlogListPage'` | Root component of the blog listing page. |
| `blogPostComponent` | `string` | `'@theme/BlogPostPage'` | Root component of each blog post page. |
| `blogTagsListComponent` | `string` | `'@theme/BlogTagsListPage'` | Root component of the tags list page. |
| `blogTagsPostsComponent` | `string` | `'@theme/BlogTagsPostsPage'` | Root component of the "posts containing tag" page. |
| `blogArchiveComponent` | `string` | `'@theme/BlogArchivePage'` | Root component of the blog archive page. |
| `remarkPlugins` | `any[]` | `[]` | Remark plugins passed to MDX. |
| `rehypePlugins` | `any[]` | `[]` | Rehype plugins passed to MDX. |
| `beforeDefaultRemarkPlugins` | `any[]` | `[]` | Custom Remark plugins passed to MDX before the default Docusaurus Remark plugins. |
| `beforeDefaultRehypePlugins` | `any[]` | `[]` | Custom Rehype plugins passed to MDX before the default Docusaurus Rehype plugins. |
| `truncateMarker` | `RegExp` | `/<!--\s*truncate\s*-->/` \| `\{\/\*\s*truncate\s*\*\/\}/` | Truncate marker marking where the summary ends. |
| `showReadingTime` | `boolean` | `true` | Show estimated reading time for the blog post. |
| `readingTime` | `ReadingTimeFn` | The default reading time | A callback to customize the reading time number displayed. |
| `authorsMapPath` | `string` | `'authors.yml'` | Path to the authors map file, relative to the blog content directory. |
| `feedOptions` | _See below_ | `{type: ['rss', 'atom']}` | Blog feed. |
| `feedOptions.type` | <code>[FeedType](#FeedType) \| [FeedType](#FeedType)[] \| 'all' \| null</code> | **Required** | Type of feed to be generated. Use `null` to disable generation. |
| `feedOptions.createFeedItems` | <code>[CreateFeedItemsFn](#CreateFeedItemsFn) \| undefined</code> | `undefined` | An optional function which can be used to transform and / or filter the items in the feed. |
| `feedOptions.limit` | `number \| null \| false` | `20` | Limits the feed to the specified number of posts, `false` or `null` for all entries. Defaults to `20`. |
| `feedOptions.title` | `string` | `siteConfig.title` | Title of the feed. |
| `feedOptions.description` | `string` | <code>\`$\{siteConfig.title} Blog\`</code> | Description of the feed. |
| `feedOptions.copyright` | `string` | `undefined` | Copyright message. |
| `feedOptions.language` | `string` (See [documentation](http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes) for possible values) | `undefined` | Language metadata of the feed. |
| `sortPosts` | <code>'descending' \| 'ascending' </code> | `'descending'` | Governs the direction of blog post sorting. |
| `processBlogPosts` | <code>[ProcessBlogPostsFn](#ProcessBlogPostsFn)</code> | `undefined` | An optional function which can be used to transform blog posts (filter, modify, delete, etc...). |
| `showLastUpdateAuthor` | `boolean` | `false` | Whether to display the author who last updated the blog post. |
| `showLastUpdateTime` | `boolean` | `false` | Whether to display the last date the blog post was updated. This requires access to git history during the build, so will not work correctly with shallow clones (a common default for CI systems). With GitHub `actions/checkout`, use`fetch-depth: 0`. |
```mdx-code-block
</APITable>
```
### Types {#types}
#### `EditUrlFn` {#EditUrlFn}
```ts
type EditUrlFunction = (params: {
blogDirPath: string;
blogPath: string;
permalink: string;
locale: string;
}) => string | undefined;
```
#### `ReadingTimeFn` {#ReadingTimeFn}
```ts
type ReadingTimeOptions = {
wordsPerMinute: number;
wordBound: (char: string) => boolean;
};
type ReadingTimeCalculator = (params: {
content: string;
frontMatter?: BlogPostFrontMatter & Record<string, unknown>;
options?: ReadingTimeOptions;
}) => number;
type ReadingTimeFn = (params: {
content: string;
frontMatter: BlogPostFrontMatter & Record<string, unknown>;
defaultReadingTime: ReadingTimeCalculator;
}) => number | undefined;
```
#### `FeedType` {#FeedType}
```ts
type FeedType = 'rss' | 'atom' | 'json';
```
#### `CreateFeedItemsFn` {#CreateFeedItemsFn}
```ts
type CreateFeedItemsFn = (params: {
blogPosts: BlogPost[];
siteConfig: DocusaurusConfig;
outDir: string;
defaultCreateFeedItemsFn: CreateFeedItemsFn;
}) => Promise<BlogFeedItem[]>;
```
#### `ProcessBlogPostsFn` {#ProcessBlogPostsFn}
```ts
type ProcessBlogPostsFn = (params: {
blogPosts: BlogPost[];
}) => Promise<void | BlogPost[]>;
```
### Example configuration {#ex-config}
You can configure this plugin through preset options or plugin options.
:::tip
Most Docusaurus users configure this plugin through the preset options.
:::
```js config-tabs
// Preset Options: blog
// Plugin Options: @docusaurus/plugin-content-blog
const config = {
path: 'blog',
// Simple use-case: string editUrl
// editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/',
// Advanced use-case: functional editUrl
editUrl: ({locale, blogDirPath, blogPath, permalink}) =>
`https://github.com/facebook/docusaurus/edit/main/website/${blogDirPath}/${blogPath}`,
editLocalizedFiles: false,
blogTitle: 'Blog title',
blogDescription: 'Blog',
blogSidebarCount: 5,
blogSidebarTitle: 'All our posts',
routeBasePath: 'blog',
include: ['**/*.{md,mdx}'],
exclude: [
'**/_*.{js,jsx,ts,tsx,md,mdx}',
'**/_*/**',
'**/*.test.{js,jsx,ts,tsx}',
'**/__tests__/**',
],
postsPerPage: 10,
blogListComponent: '@theme/BlogListPage',
blogPostComponent: '@theme/BlogPostPage',
blogTagsListComponent: '@theme/BlogTagsListPage',
blogTagsPostsComponent: '@theme/BlogTagsPostsPage',
remarkPlugins: [require('./my-remark-plugin')],
rehypePlugins: [],
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
truncateMarker: /<!--\s*(truncate)\s*-->/,
showReadingTime: true,
feedOptions: {
type: '',
title: '',
description: '',
copyright: '',
language: undefined,
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,
});
},
},
};
```
## Markdown front matter {#markdown-front-matter}
Markdown documents can use the following Markdown [front matter](../../guides/markdown-features/markdown-features-intro.mdx#front-matter) metadata fields, enclosed by a line `---` on either side.
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `authors` | `Authors` | `undefined` | List of blog post authors (or unique author). Read the [`authors` guide](../../blog.mdx#blog-post-authors) for more explanations. Prefer `authors` over the `author_*` front matter fields, even for single author blog posts. |
| `author` | `string` | `undefined` | ⚠️ Prefer using `authors`. The blog post author's name. |
| `author_url` | `string` | `undefined` | ⚠️ Prefer using `authors`. The URL that the author's name will be linked to. This could be a GitHub, Twitter, Facebook profile URL, etc. |
| `author_image_url` | `string` | `undefined` | ⚠️ Prefer using `authors`. The URL to the author's thumbnail image. |
| `author_title` | `string` | `undefined` | ⚠️ Prefer using `authors`. A description of the author. |
| `title` | `string` | Markdown title | The blog post title. |
| `date` | `string` | File name or file creation time | The blog post creation date. If not specified, this can be extracted from the file or folder name, e.g, `2021-04-15-blog-post.mdx`, `2021-04-15-blog-post/index.mdx`, `2021/04/15/blog-post.mdx`. Otherwise, it is the Markdown file creation time. |
| `tags` | `Tag[]` | `undefined` | A list of strings or objects of two string fields `label` and `permalink` to tag to your post. |
| `draft` | `boolean` | `false` | Draft blog posts will only be available during development. |
| `unlisted` | `boolean` | `false` | Unlisted blog posts will be available in both development and production. They will be "hidden" in production, not indexed, excluded from sitemaps, and can only be accessed by users having a direct link. |
| `hide_table_of_contents` | `boolean` | `false` | Whether to hide the table of contents to the right. |
| `toc_min_heading_level` | `number` | `2` | The minimum heading level shown in the table of contents. Must be between 2 and 6 and lower or equal to the max value. |
| `toc_max_heading_level` | `number` | `3` | The max heading level shown in the table of contents. Must be between 2 and 6. |
| `keywords` | `string[]` | `undefined` | Keywords meta tag, which will become the `<meta name="keywords" content="keyword1,keyword2,..."/>` in `<head>`, used by search engines. |
| `description` | `string` | The first line of Markdown content | The description of your document, which will become the `<meta name="description" content="..."/>` and `<meta property="og:description" content="..."/>` in `<head>`, used by search engines. |
| `image` | `string` | `undefined` | Cover or thumbnail image that will be used as the `<meta property="og:image" content="..."/>` in the `<head>`, enhancing link previews on social media and messaging platforms. |
| `slug` | `string` | File path | Allows to customize the blog post URL (`/<routeBasePath>/<slug>`). Support multiple patterns: `slug: my-blog-post`, `slug: /my/path/to/blog/post`, slug: `/`. |
| `last_update` | `FrontMatterLastUpdate` | `undefined` | Allows overriding the last update author/date. Date can be any [parsable date string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse). |
```mdx-code-block
</APITable>
```
```ts
type FrontMatterLastUpdate = {date?: string; author?: string};
type Tag = string | {label: string; permalink: string};
// An author key references an author from the global plugin authors.yml file
type AuthorKey = string;
type Author = {
key?: AuthorKey;
name: string;
title?: string;
url?: string;
image_url?: string;
};
// The front matter authors field allows various possible shapes
type Authors = AuthorKey | Author | (AuthorKey | Author)[];
```
Example:
```md
---
title: Welcome Docusaurus
authors:
- slorber
- yangshun
- name: Joel Marcey
title: Co-creator of Docusaurus 1
url: https://github.com/JoelMarcey
image_url: https://github.com/JoelMarcey.png
tags: [hello, docusaurus-v2]
description: This is my first post on Docusaurus.
image: https://i.imgur.com/mErPwqL.png
hide_table_of_contents: false
---
A Markdown blog post
```
## i18n {#i18n}
Read the [i18n introduction](../../i18n/i18n-introduction.mdx) first.
### Translation files location {#translation-files-location}
- **Base path**: `website/i18n/[locale]/docusaurus-plugin-content-blog`
- **Multi-instance path**: `website/i18n/[locale]/docusaurus-plugin-content-blog-[pluginId]`
- **JSON files**: extracted with [`docusaurus write-translations`](../../cli.mdx#docusaurus-write-translations-sitedir)
- **Markdown files**: `website/i18n/[locale]/docusaurus-plugin-content-blog`
### Example file-system structure {#example-file-system-structure}
```bash
website/i18n/[locale]/docusaurus-plugin-content-blog
│ # translations for website/blog
├── authors.yml
├── first-blog-post.md
├── second-blog-post.md
│ # translations for the plugin options that will be rendered
└── options.json
```

View file

@ -0,0 +1,368 @@
---
sidebar_position: 1
slug: /api/plugins/@docusaurus/plugin-content-docs
---
# 📦 plugin-content-docs
import APITable from '@site/src/components/APITable';
Provides the [Docs](../../guides/docs/docs-introduction.mdx) functionality and is the default docs plugin for Docusaurus.
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-content-docs
```
:::tip
If you use the preset `@docusaurus/preset-classic`, you don't need to install this plugin as a dependency.
You can configure this plugin through the [preset options](../../using-plugins.mdx#docusauruspreset-classic).
:::
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `path` | `string` | `'docs'` | Path to the docs content directory on the file system, relative to site directory. |
| `editUrl` | <code>string \| [EditUrlFunction](#EditUrlFunction)</code> | `undefined` | Base URL to edit your site. The final URL is computed by `editUrl + relativeDocPath`. Using a function allows more nuanced control for each file. Omitting this variable entirely will disable edit links. |
| `editLocalizedFiles` | `boolean` | `false` | The edit URL will target the localized file, instead of the original unlocalized file. Ignored when `editUrl` is a function. |
| `editCurrentVersion` | `boolean` | `false` | The edit URL will always target the current version doc instead of older versions. Ignored when `editUrl` is a function. |
| `routeBasePath` | `string` | `'docs'` | URL route for the docs section of your site. **DO NOT** include a trailing slash. Use `/` for shipping docs without base path. |
| `tagsBasePath` | `string` | `'tags'` | URL route for the tags list page of your site. It is prepended to the `routeBasePath`. |
| `include` | `string[]` | `['**/*.{md,mdx}']` | Array of glob patterns matching Markdown files to be built, relative to the content path. |
| `exclude` | `string[]` | _See example configuration_ | Array of glob patterns matching Markdown files to be excluded. Serves as refinement based on the `include` option. |
| `sidebarPath` | <code>false \| string</code> | `undefined` | Path to sidebar configuration. Use `false` to disable sidebars, or `undefined` to create a fully autogenerated sidebar. |
| `sidebarCollapsible` | `boolean` | `true` | Whether sidebar categories are collapsible by default. See also [Collapsible categories](/docs/sidebar/items#collapsible-categories) |
| `sidebarCollapsed` | `boolean` | `true` | Whether sidebar categories are collapsed by default. See also [Expanded categories by default](/docs/sidebar/items#expanded-categories-by-default) |
| `sidebarItemsGenerator` | <code>[SidebarGenerator](#SidebarGenerator)</code> | _Omitted_ | Function used to replace the sidebar items of type `'autogenerated'` with real sidebar items (docs, categories, links...). See also [Customize the sidebar items generator](/docs/sidebar/autogenerated#customize-the-sidebar-items-generator) |
| `numberPrefixParser` | <code>boolean \| [PrefixParser](#PrefixParser)</code> | _Omitted_ | Custom parsing logic to extract number prefixes from file names. Use `false` to disable this behavior and leave the docs untouched, and `true` to use the default parser. See also [Using number prefixes](/docs/sidebar/autogenerated#using-number-prefixes) |
| `docsRootComponent` | `string` | `'@theme/DocsRoot'` | Parent component of all the docs plugin pages (including all versions). Stays mounted when navigation between docs pages and versions. |
| `docVersionRootComponent` | `string` | `'@theme/DocVersionLayout'` | Parent component of all docs pages of an individual version (doc pages with sidebars, tags pages). Stays mounted when navigation between pages of that specific version. |
| `docRootComponent` | `string` | `'@theme/DocPage'` | Parent component of all doc pages with sidebars (regular docs pages, category generated index pages). Stays mounted when navigation between such pages. |
| `docItemComponent` | `string` | `'@theme/DocItem'` | Main doc container, with TOC, pagination, etc. |
| `docTagsListComponent` | `string` | `'@theme/DocTagsListPage'` | Root component of the tags list page |
| `docTagDocListComponent` | `string` | `'@theme/DocTagDocListPage'` | Root component of the "docs containing tag X" page. |
| `docCategoryGeneratedIndexComponent` | `string` | `'@theme/DocCategoryGeneratedIndexPage'` | Root component of the generated category index page. |
| `remarkPlugins` | `any[]` | `[]` | Remark plugins passed to MDX. |
| `rehypePlugins` | `any[]` | `[]` | Rehype plugins passed to MDX. |
| `beforeDefaultRemarkPlugins` | `any[]` | `[]` | Custom Remark plugins passed to MDX before the default Docusaurus Remark plugins. |
| `beforeDefaultRehypePlugins` | `any[]` | `[]` | Custom Rehype plugins passed to MDX before the default Docusaurus Rehype plugins. |
| `showLastUpdateAuthor` | `boolean` | `false` | Whether to display the author who last updated the doc. |
| `showLastUpdateTime` | `boolean` | `false` | Whether to display the last date the doc was updated. This requires access to git history during the build, so will not work correctly with shallow clones (a common default for CI systems). With GitHub `actions/checkout`, use`fetch-depth: 0`. |
| `breadcrumbs` | `boolean` | `true` | Enable or disable the breadcrumbs on doc pages. |
| `disableVersioning` | `boolean` | `false` | Explicitly disable versioning even when multiple versions exist. This will make the site only include the current version. Will error if `includeCurrentVersion: false` and `disableVersioning: true`. |
| `includeCurrentVersion` | `boolean` | `true` | Include the current version of your docs. |
| `lastVersion` | `string` | First version in `versions.json` | The version navigated to in priority and displayed by default for docs navbar items. |
| `onlyIncludeVersions` | `string[]` | All versions available | Only include a subset of all available versions. |
| `versions` | <code>[VersionsConfig](#VersionsConfig)</code> | `{}` | Independent customization of each version's properties. |
```mdx-code-block
</APITable>
```
### Types {#types}
#### `EditUrlFunction` {#EditUrlFunction}
```ts
type EditUrlFunction = (params: {
version: string;
versionDocsDirPath: string;
docPath: string;
permalink: string;
locale: string;
}) => string | undefined;
```
#### `PrefixParser` {#PrefixParser}
```ts
type PrefixParser = (filename: string) => {
filename: string;
numberPrefix?: number;
};
```
#### `SidebarGenerator` {#SidebarGenerator}
```ts
type SidebarGenerator = (generatorArgs: {
/** The sidebar item with type "autogenerated" to be transformed. */
item: {type: 'autogenerated'; dirName: string};
/** Useful metadata for the version this sidebar belongs to. */
version: {contentPath: string; versionName: string};
/** All the docs of that version (unfiltered). */
docs: {
id: string;
title: string;
frontMatter: DocFrontMatter & Record<string, unknown>;
source: string;
sourceDirName: string;
sidebarPosition?: number | undefined;
}[];
/** Number prefix parser configured for this plugin. */
numberPrefixParser: PrefixParser;
/** The default category index matcher which you can override. */
isCategoryIndex: CategoryIndexMatcher;
/**
* key is the path relative to the doc content directory, value is the
* category metadata file's content.
*/
categoriesMetadata: {[filePath: string]: CategoryMetadata};
/**
* Useful to re-use/enhance the default sidebar generation logic from
* Docusaurus.
*/
defaultSidebarItemsGenerator: SidebarGenerator;
// Returns an array of sidebar items — same as what you can declare in
// sidebars.js, except for shorthands. See https://docusaurus.io/docs/sidebar/items
}) => Promise<SidebarItem[]>;
type CategoryIndexMatcher = (param: {
/** The file name, without extension */
fileName: string;
/**
* The list of directories, from lowest level to highest.
* If there's no dir name, directories is ['.']
*/
directories: string[];
/** The extension, with a leading dot */
extension: string;
}) => boolean;
```
#### `VersionsConfig` {#VersionsConfig}
```ts
type VersionConfig = {
/**
* The base path of the version, will be appended to `baseUrl` +
* `routeBasePath`.
*/
path?: string;
/** The label of the version to be used in badges, dropdowns, etc. */
label?: string;
/** The banner to show at the top of a doc of that version. */
banner?: 'none' | 'unreleased' | 'unmaintained';
/** Show a badge with the version label at the top of each doc. */
badge?: boolean;
/** Prevents search engines from indexing this version */
noIndex?: boolean;
/** Add a custom class name to the <html> element of each doc */
className?: string;
};
type VersionsConfig = {[versionName: string]: VersionConfig};
```
### Example configuration {#ex-config}
You can configure this plugin through preset options or plugin options.
:::tip
Most Docusaurus users configure this plugin through the preset options.
:::
```js config-tabs
// Preset Options: docs
// Plugin Options: @docusaurus/plugin-content-docs
const config = {
path: 'docs',
breadcrumbs: true,
// Simple use-case: string editUrl
// editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/',
// Advanced use-case: functional editUrl
editUrl: ({versionDocsDirPath, docPath}) =>
`https://github.com/facebook/docusaurus/edit/main/website/${versionDocsDirPath}/${docPath}`,
editLocalizedFiles: false,
editCurrentVersion: false,
routeBasePath: 'docs',
include: ['**/*.md', '**/*.mdx'],
exclude: [
'**/_*.{js,jsx,ts,tsx,md,mdx}',
'**/_*/**',
'**/*.test.{js,jsx,ts,tsx}',
'**/__tests__/**',
],
sidebarPath: 'sidebars.js',
async sidebarItemsGenerator({
defaultSidebarItemsGenerator,
numberPrefixParser,
item,
version,
docs,
isCategoryIndex,
}) {
// Use the provided data to generate a custom sidebar slice
return [
{type: 'doc', id: 'intro'},
{
type: 'category',
label: 'Tutorials',
items: [
{type: 'doc', id: 'tutorial1'},
{type: 'doc', id: 'tutorial2'},
],
},
];
},
numberPrefixParser(filename) {
// Implement your own logic to extract a potential number prefix
const numberPrefix = findNumberPrefix(filename);
// Prefix found: return it with the cleaned filename
if (numberPrefix) {
return {
numberPrefix,
filename: filename.replace(prefix, ''),
};
}
// No number prefix found
return {numberPrefix: undefined, filename};
},
docsRootComponent: '@theme/DocsRoot',
docVersionRootComponent: '@theme/DocVersionRoot',
docRootComponent: '@theme/DocRoot',
docItemComponent: '@theme/DocItem',
remarkPlugins: [require('./my-remark-plugin')],
rehypePlugins: [],
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
showLastUpdateAuthor: false,
showLastUpdateTime: false,
disableVersioning: false,
includeCurrentVersion: true,
lastVersion: undefined,
versions: {
current: {
label: 'Android SDK v2.0.0 (WIP)',
path: 'android-2.0.0',
banner: 'none',
},
'1.0.0': {
label: 'Android SDK v1.0.0',
path: 'android-1.0.0',
banner: 'unmaintained',
},
},
onlyIncludeVersions: ['current', '1.0.0', '2.0.0'],
};
```
## Markdown front matter {#markdown-front-matter}
Markdown documents can use the following Markdown [front matter](../../guides/markdown-features/markdown-features-intro.mdx#front-matter) metadata fields, enclosed by a line `---` on either side.
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `string` | file path (including folders, without the extension) | A unique document ID. |
| `title` | `string` | Markdown title or `id` | The text title of your document. Used for the page metadata and as a fallback value in multiple places (sidebar, next/previous buttons...). Automatically added at the top of your doc if it does not contain any Markdown title. |
| `pagination_label` | `string` | `sidebar_label` or `title` | The text used in the document next/previous buttons for this document. |
| `sidebar_label` | `string` | `title` | The text shown in the document sidebar for this document. |
| `sidebar_position` | `number` | Default ordering | Controls the position of a doc inside the generated sidebar slice when using `autogenerated` sidebar items. See also [Autogenerated sidebar metadata](/docs/sidebar/autogenerated#autogenerated-sidebar-metadata). |
| `sidebar_class_name` | `string` | `undefined` | Gives the corresponding sidebar label a special class name when using autogenerated sidebars. |
| `sidebar_custom_props` | `object` | `undefined` | Assign [custom props](../../guides/docs/sidebar/index.mdx#passing-custom-props) to the sidebar item referencing this doc |
| `displayed_sidebar` | `string` | `undefined` | Force the display of a given sidebar when browsing the current document. Read the [multiple sidebars guide](../../guides/docs/sidebar/multiple-sidebars.mdx) for details. |
| `hide_title` | `boolean` | `false` | Whether to hide the title at the top of the doc. It only hides a title declared through the front matter, and have no effect on a Markdown title at the top of your document. |
| `hide_table_of_contents` | `boolean` | `false` | Whether to hide the table of contents to the right. |
| `toc_min_heading_level` | `number` | `2` | The minimum heading level shown in the table of contents. Must be between 2 and 6 and lower or equal to the max value. |
| `toc_max_heading_level` | `number` | `3` | The max heading level shown in the table of contents. Must be between 2 and 6. |
| `pagination_next` | <code>string \| null</code> | Next doc in the sidebar | The ID of the documentation you want the "Next" pagination to link to. Use `null` to disable showing "Next" for this page. |
| `pagination_prev` | <code>string \| null</code> | Previous doc in the sidebar | The ID of the documentation you want the "Previous" pagination to link to. Use `null` to disable showing "Previous" for this page. |
| `parse_number_prefixes` | `boolean` | `numberPrefixParser` plugin option | Whether number prefix parsing is disabled on this doc. See also [Using number prefixes](/docs/sidebar/autogenerated#using-number-prefixes). |
| `custom_edit_url` | <code>string \| null</code> | Computed using the `editUrl` plugin option | The URL for editing this document. Use `null` to disable showing "Edit this page" for this page. |
| `keywords` | `string[]` | `undefined` | Keywords meta tag for the document page, for search engines. |
| `description` | `string` | The first line of Markdown content | The description of your document, which will become the `<meta name="description" content="..."/>` and `<meta property="og:description" content="..."/>` in `<head>`, used by search engines. |
| `image` | `string` | `undefined` | Cover or thumbnail image that will be used as the `<meta property="og:image" content="..."/>` in the `<head>`, enhancing link previews on social media and messaging platforms. |
| `slug` | `string` | File path | Allows to customize the document URL (`/<routeBasePath>/<slug>`). Support multiple patterns: `slug: my-doc`, `slug: /my/path/myDoc`, `slug: /`. |
| `tags` | `Tag[]` | `undefined` | A list of strings or objects of two string fields `label` and `permalink` to tag to your docs. |
| `draft` | `boolean` | `false` | Draft documents will only be available during development. |
| `unlisted` | `boolean` | `false` | Unlisted documents will be available in both development and production. They will be "hidden" in production, not indexed, excluded from sitemaps, and can only be accessed by users having a direct link. |
| `last_update` | `FrontMatterLastUpdate` | `undefined` | Allows overriding the last update author/date. Date can be any [parsable date string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse). |
```mdx-code-block
</APITable>
```
```ts
type FrontMatterLastUpdate = {date?: string; author?: string};
type Tag = string | {label: string; permalink: string};
```
Example:
```md
---
id: doc-markdown
title: Docs Markdown Features
hide_title: false
hide_table_of_contents: false
sidebar_label: Markdown
sidebar_position: 3
pagination_label: Markdown features
custom_edit_url: https://github.com/facebook/docusaurus/edit/main/docs/api-doc-markdown.md
description: How do I find you when I cannot solve this problem
keywords:
- docs
- docusaurus
image: https://i.imgur.com/mErPwqL.png
slug: /myDoc
last_update:
date: 1/1/2000
author: custom author name
---
# Markdown Features
My Document Markdown content
```
## i18n {#i18n}
Read the [i18n introduction](../../i18n/i18n-introduction.mdx) first.
### Translation files location {#translation-files-location}
- **Base path**: `website/i18n/[locale]/docusaurus-plugin-content-docs`
- **Multi-instance path**: `website/i18n/[locale]/docusaurus-plugin-content-docs-[pluginId]`
- **JSON files**: extracted with [`docusaurus write-translations`](../../cli.mdx#docusaurus-write-translations-sitedir)
- **Markdown files**: `website/i18n/[locale]/docusaurus-plugin-content-docs/[versionName]`
### Example file-system structure {#example-file-system-structure}
```bash
website/i18n/[locale]/docusaurus-plugin-content-docs
│ # translations for website/docs
├── current
│ ├── api
│ │ └── config.md
│ └── getting-started.md
├── current.json
│ # translations for website/versioned_docs/version-1.0.0
├── version-1.0.0
│ ├── api
│ │ └── config.md
│ └── getting-started.md
└── version-1.0.0.json
```

View file

@ -0,0 +1,140 @@
---
sidebar_position: 3
slug: /api/plugins/@docusaurus/plugin-content-pages
---
# 📦 plugin-content-pages
import APITable from '@site/src/components/APITable';
The default pages plugin for Docusaurus. The classic template ships with this plugin with default configurations. This plugin provides [creating pages](guides/creating-pages.mdx) functionality.
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-content-pages
```
:::tip
If you use the preset `@docusaurus/preset-classic`, you don't need to install this plugin as a dependency.
You can configure this plugin through the [preset options](../../using-plugins.mdx#docusauruspreset-classic).
:::
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `path` | `string` | `'src/pages'` | Path to data on filesystem relative to site dir. Components in this directory will be automatically converted to pages. |
| `routeBasePath` | `string` | `'/'` | URL route for the pages section of your site. **DO NOT** include a trailing slash. |
| `include` | `string[]` | `['**/*.{js,jsx,ts,tsx,md,mdx}']` | Matching files will be included and processed. |
| `exclude` | `string[]` | _See example configuration_ | No route will be created for matching files. |
| `mdxPageComponent` | `string` | `'@theme/MDXPage'` | Component used by each MDX page. |
| `remarkPlugins` | `[]` | `any[]` | Remark plugins passed to MDX. |
| `rehypePlugins` | `[]` | `any[]` | Rehype plugins passed to MDX. |
| `beforeDefaultRemarkPlugins` | `any[]` | `[]` | Custom Remark plugins passed to MDX before the default Docusaurus Remark plugins. |
| `beforeDefaultRehypePlugins` | `any[]` | `[]` | Custom Rehype plugins passed to MDX before the default Docusaurus Rehype plugins. |
```mdx-code-block
</APITable>
```
### Example configuration {#ex-config}
You can configure this plugin through preset options or plugin options.
:::tip
Most Docusaurus users configure this plugin through the preset options.
:::
```js config-tabs
// Preset Options: pages
// Plugin Options: @docusaurus/plugin-content-pages
const config = {
path: 'src/pages',
routeBasePath: '',
include: ['**/*.{js,jsx,ts,tsx,md,mdx}'],
exclude: [
'**/_*.{js,jsx,ts,tsx,md,mdx}',
'**/_*/**',
'**/*.test.{js,jsx,ts,tsx}',
'**/__tests__/**',
],
mdxPageComponent: '@theme/MDXPage',
remarkPlugins: [require('./my-remark-plugin')],
rehypePlugins: [],
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
};
```
## Markdown front matter {#markdown-front-matter}
Markdown pages can use the following Markdown [front matter](../../guides/markdown-features/markdown-features-intro.mdx#front-matter) metadata fields, enclosed by a line `---` on either side.
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `title` | `string` | Markdown title | The blog post title. |
| `description` | `string` | The first line of Markdown content | The description of your page, which will become the `<meta name="description" content="..."/>` and `<meta property="og:description" content="..."/>` in `<head>`, used by search engines. |
| `keywords` | `string[]` | `undefined` | Keywords meta tag, which will become the `<meta name="keywords" content="keyword1,keyword2,..."/>` in `<head>`, used by search engines. |
| `image` | `string` | `undefined` | Cover or thumbnail image that will be used as the `<meta property="og:image" content="..."/>` in the `<head>`, enhancing link previews on social media and messaging platforms. |
| `wrapperClassName` | `string` | | Class name to be added to the wrapper element to allow targeting specific page content. |
| `hide_table_of_contents` | `boolean` | `false` | Whether to hide the table of contents to the right. |
| `draft` | `boolean` | `false` | Draft pages will only be available during development. |
| `unlisted` | `boolean` | `false` | Unlisted pages will be available in both development and production. They will be "hidden" in production, not indexed, excluded from sitemaps, and can only be accessed by users having a direct link. |
```mdx-code-block
</APITable>
```
Example:
```md
---
title: Markdown Page
description: Markdown page SEO description
wrapperClassName: markdown-page
hide_table_of_contents: false
draft: true
---
Markdown page content
```
## i18n {#i18n}
Read the [i18n introduction](../../i18n/i18n-introduction.mdx) first.
### Translation files location {#translation-files-location}
- **Base path**: `website/i18n/[locale]/docusaurus-plugin-content-pages`
- **Multi-instance path**: `website/i18n/[locale]/docusaurus-plugin-content-pages-[pluginId]`
- **JSON files**: extracted with [`docusaurus write-translations`](../../cli.mdx#docusaurus-write-translations-sitedir)
- **Markdown files**: `website/i18n/[locale]/docusaurus-plugin-content-pages`
### Example file-system structure {#example-file-system-structure}
```bash
website/i18n/[locale]/docusaurus-plugin-content-pages
│ # translations for website/src/pages
├── first-markdown-page.md
└── second-markdown-page.md
```

View file

@ -0,0 +1,108 @@
---
sidebar_position: 5
slug: /api/plugins/@docusaurus/plugin-debug
---
# 📦 plugin-debug
```mdx-code-block
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
```
The debug plugin will display useful debug information at [`http://localhost:3000/__docusaurus/debug`](http://localhost:3000/__docusaurus/debug).
It is mostly useful for plugin authors, that will be able to inspect more easily the content of the `.docusaurus` folder (like the creates routes), but also be able to inspect data structures that are never written to disk, like the plugin data loaded through the `contentLoaded` lifecycle.
:::info
If you use the plugin via the classic preset, the preset will **enable the plugin in development and disable it in production** by default (`debug: undefined`) to avoid exposing potentially sensitive information. You can use `debug: true` to always enable it or `debug: false` to always disable it.
If you use a standalone plugin, you may need to achieve the same effect by checking the environment:
```js title="docusaurus.config.js"
export default {
plugins: [
// highlight-next-line
process.env.NODE_ENV === 'production' && '@docusaurus/plugin-debug',
].filter(Boolean),
};
```
:::
:::note
If you report a bug, we will probably ask you to have this plugin turned on in the production, so that we can inspect your deployment config more easily.
If you don't have any sensitive information, you can keep it on in production [like we do](/__docusaurus/debug).
:::
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-debug
```
:::tip
If you use the preset `@docusaurus/preset-classic`, you don't need to install this plugin as a dependency.
You can configure this plugin through the [preset options](../../using-plugins.mdx#docusauruspreset-classic).
:::
## Configuration {#configuration}
This plugin currently has no options.
### Example configuration {#ex-config}
You can configure this plugin through preset options or plugin options.
:::tip
Most Docusaurus users configure this plugin through the preset options.
:::
```mdx-code-block
<Tabs groupId="api-config-ex">
<TabItem value="preset" label="Preset options">
```
If you use a preset, configure this plugin through the [preset options](../../using-plugins.mdx#docusauruspreset-classic):
```js title="docusaurus.config.js"
export default {
presets: [
[
'@docusaurus/preset-classic',
{
// highlight-next-line
debug: true, // This will enable the plugin in production
},
],
],
};
```
```mdx-code-block
</TabItem>
<TabItem value="plugin" label="Plugin Options">
```
If you are using a standalone plugin, provide options directly to the plugin:
```js title="docusaurus.config.js"
export default {
// highlight-next-line
plugins: ['@docusaurus/plugin-debug'],
};
```
```mdx-code-block
</TabItem>
</Tabs>
```

View file

@ -0,0 +1,77 @@
---
sidebar_position: 6
slug: /api/plugins/@docusaurus/plugin-google-analytics
---
# 📦 plugin-google-analytics
import APITable from '@site/src/components/APITable';
The default [Google Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/) plugin. It is a JavaScript library for measuring how users interact with your website **in the production build**. If you are using Google Analytics 4 you might need to consider using [plugin-google-gtag](./plugin-google-gtag.mdx) instead.
:::danger Deprecated
This plugin is **deprecated**, and will become useless on July 1, 2023.
Google is [moving away from Universal Analytics](https://blog.google/products/marketingplatform/analytics/prepare-for-future-with-google-analytics-4/).
If you are still using this plugin with a `UA-*` tracking id, you should create a Google Analytics 4 account as soon as possible, and use [`@docusaurus/plugin-google-gtag`](./plugin-google-gtag.mdx) instead of this plugin. More details [here](https://github.com/facebook/docusaurus/issues/7221).
:::
:::warning production only
This plugin is always inactive in development and **only active in production** to avoid polluting the analytics statistics.
:::
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-google-analytics
```
:::tip
If you use the preset `@docusaurus/preset-classic`, you don't need to install this plugin as a dependency.
You can configure this plugin through the [preset options](../../using-plugins.mdx#docusauruspreset-classic).
:::
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `trackingID` | `string` | **Required** | The tracking ID of your analytics service. |
| `anonymizeIP` | `boolean` | `false` | Whether the IP should be anonymized when sending requests. |
```mdx-code-block
</APITable>
```
### Example configuration {#ex-config}
You can configure this plugin through preset options or plugin options.
:::tip
Most Docusaurus users configure this plugin through the preset options.
:::
```js config-tabs
// Preset Options: googleAnalytics
// Plugin Options: @docusaurus/plugin-google-analytics
const config = {
trackingID: 'UA-141789564-1',
anonymizeIP: true,
};
```

View file

@ -0,0 +1,73 @@
---
sidebar_position: 7
slug: /api/plugins/@docusaurus/plugin-google-gtag
---
# 📦 plugin-google-gtag
import APITable from '@site/src/components/APITable';
The default [Global Site Tag (gtag.js)](https://developers.google.com/analytics/devguides/collection/gtagjs/) plugin. It is a JavaScript tagging framework and API that allows you to send event data to Google Analytics, Google Ads, and Google Marketing Platform. This section describes how to configure a Docusaurus site to enable global site tag for Google Analytics.
:::tip
You can use [Google's Tag Assistant](https://tagassistant.google.com/) tool to check if your gtag is set up correctly!
:::
:::warning production only
This plugin is always inactive in development and **only active in production** to avoid polluting the analytics statistics.
:::
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-google-gtag
```
:::tip
If you use the preset `@docusaurus/preset-classic`, you don't need to install this plugin as a dependency.
You can configure this plugin through the [preset options](../../using-plugins.mdx#docusauruspreset-classic).
:::
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `trackingID` | <code>string \| string[]</code> | **Required** | The tracking ID of your gtag service. It is possible to provide multiple ids. |
| `anonymizeIP` | `boolean` | `false` | Whether the IP should be anonymized when sending requests. |
```mdx-code-block
</APITable>
```
### Example configuration {#ex-config}
You can configure this plugin through preset options or plugin options.
:::tip
Most Docusaurus users configure this plugin through the preset options.
:::
```js config-tabs
// Preset Options: gtag
// Plugin Options: @docusaurus/plugin-google-gtag
const config = {
trackingID: 'G-999X9XX9XX',
anonymizeIP: true,
};
```

View file

@ -0,0 +1,71 @@
---
sidebar_position: 8
slug: /api/plugins/@docusaurus/plugin-google-tag-manager
---
# 📦 plugin-google-tag-manager
import APITable from '@site/src/components/APITable';
A plugin for adding [Google Tag Manager (gtm.js)](https://developers.google.com/tag-platform/tag-manager) to a Docusaurus site. Use this plugin in conjunction with the standard [gtag plugin](./plugin-google-gtag.mdx) for in-depth analysis of how users are using your site.
:::tip
You can use [Google's Tag Assistant](https://tagassistant.google.com/) tool to check if tag manager is set up correctly!
:::
:::warning production only
This plugin is always inactive in development and **only active in production** to avoid polluting the analytics statistics.
:::
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-google-tag-manager
```
:::tip
If you use the preset `@docusaurus/preset-classic`, you don't need to install this plugin as a dependency.
You can configure this plugin through the [preset options](../../using-plugins.mdx#docusauruspreset-classic).
:::
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `containerId` | `string` | **Required** | Your Tag Manager container Id (usually starts with `GTM-`). |
```mdx-code-block
</APITable>
```
### Example configuration {#ex-config}
You can configure this plugin through preset options or plugin options.
:::tip
Most Docusaurus users configure this plugin through the preset options.
:::
```js config-tabs
// Preset Options: googleTagManager
// Plugin Options: @docusaurus/plugin-google-tag-manager
const config = {
containerId: 'GTM-12345',
};
```

View file

@ -0,0 +1,92 @@
---
sidebar_position: 8
slug: /api/plugins/@docusaurus/plugin-ideal-image
---
# 📦 plugin-ideal-image
import APITable from '@site/src/components/APITable';
Docusaurus Plugin to generate an almost ideal image (responsive, lazy-loading, and low quality placeholder).
:::info
By default, the plugin is **inactive in development** so you could always view full-scale images. If you want to debug the ideal image behavior, you could set the [`disableInDev`](#disableInDev) option to `false`.
:::
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-ideal-image
```
## Usage {#usage}
This plugin supports the PNG and JPG formats only.
```jsx
import Image from '@theme/IdealImage';
import thumbnail from './path/to/img.png';
// your React code
<Image img={thumbnail} />
// or
<Image img={require('./path/to/img.png')} />
```
:::warning
This plugin registers a [Webpack loader](https://webpack.js.org/loaders/) that changes the type of imported/require images:
- Before: `string`
- After: `{preSrc: string, src: import("@theme/IdealImage").SrcImage}`
:::
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | `ideal-img/[name].[hash:hex:7].[width].[ext]` | Filename template for output files. |
| `sizes` | `number[]` | _original size_ | Specify all widths you want to use. If a specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up). |
| `size` | `number` | _original size_ | Specify one width you want to use; if the specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up) |
| `min` | `number` | | As an alternative to manually specifying `sizes`, you can specify `min`, `max` and `steps`, and the sizes will be generated for you. |
| `max` | `number` | | See `min` above |
| `steps` | `number` | `4` | Configure the number of images generated between `min` and `max` (inclusive) |
| `quality` | `number` | `85` | JPEG compression quality |
| `disableInDev` | `boolean` | `true` | You can test ideal image behavior in dev mode by setting this to `false`. **Tip**: use [network throttling](https://www.browserstack.com/guide/how-to-perform-network-throttling-in-chrome) in your browser to simulate slow networks. |
```mdx-code-block
</APITable>
```
### Example configuration {#ex-config}
Here's an example configuration:
```js title="docusaurus.config.js"
export default {
plugins: [
[
'@docusaurus/plugin-ideal-image',
// highlight-start
{
quality: 70,
max: 1030, // max resized image's size.
min: 640, // min resized image's size. if original is lower, use that size.
steps: 2, // the max number of images generated between min and max (inclusive)
disableInDev: false,
},
// highlight-end
],
],
};
```

View file

@ -0,0 +1,303 @@
---
sidebar_position: 9
slug: /api/plugins/@docusaurus/plugin-pwa
---
# 📦 plugin-pwa
Docusaurus Plugin to add PWA support using [Workbox](https://developers.google.com/web/tools/workbox). This plugin generates a [Service Worker](https://developers.google.com/web/fundamentals/primers/service-workers) in production build only, and allows you to create fully PWA-compliant documentation site with offline and installation support.
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-pwa
```
## Configuration {#configuration}
Create a [PWA manifest](https://web.dev/add-manifest/) at `./static/manifest.json`.
Modify `docusaurus.config.js` with a minimal PWA config, like:
```js title="docusaurus.config.js"
export default {
plugins: [
[
'@docusaurus/plugin-pwa',
{
debug: true,
offlineModeActivationStrategies: [
'appInstalled',
'standalone',
'queryString',
],
pwaHead: [
{
tagName: 'link',
rel: 'icon',
href: '/img/docusaurus.png',
},
{
tagName: 'link',
rel: 'manifest',
href: '/manifest.json', // your PWA manifest
},
{
tagName: 'meta',
name: 'theme-color',
content: 'rgb(37, 194, 160)',
},
],
},
],
],
};
```
## Progressive Web App {#progressive-web-app}
Having a service worker installed is not enough to make your application a PWA. You'll need to at least include a [Web App Manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest) and have the correct tags in `<head>` ([Options > pwaHead](#pwahead)).
After deployment, you can use [Lighthouse](https://developers.google.com/web/tools/lighthouse) to run an audit on your site.
For a more exhaustive list of what it takes for your site to be a PWA, refer to the [PWA Checklist](https://developers.google.com/web/progressive-web-apps/checklist)
## App installation support {#app-installation-support}
If your browser supports it, you should be able to install a Docusaurus site as an app.
![A screen recording of the installation process. A button appears in the address bar of the browser, which displays a dialog asking "install this application?" when clicked. After clicking the "Install" button, a new application is opened in the operating system, opening to the Docusaurus homepage.](/img/pwa_install.gif)
:::note
App installation requires the HTTPS protocol and a valid manifest.
:::
## Offline mode (precaching) {#offline-mode-precaching}
We enable users to browse a Docusaurus site offline, by using service-worker precaching.
The [workbox-precaching](https://developers.google.com/web/tools/workbox/modules/workbox-precaching) page explains the idea:
> One feature of service workers is the ability to save a set of files to the cache when the service worker is installing. This is often referred to as "precaching", since you are caching content ahead of the service worker being used.
>
> The main reason for doing this is that it gives developers control over the cache, meaning they can determine when and how long a file is cached as well as serve it to the browser without going to the network, meaning it can be used to create web apps that work offline.
>
> Workbox takes a lot of the heavy lifting out of precaching by simplifying the API and ensuring assets are downloaded efficiently.
By default, offline mode is enabled when the site is installed as an app. See the `offlineModeActivationStrategies` option for details.
After the site has been precached, the service worker will serve cached responses for later visits. When a new build is deployed along with a new service worker, the new one will begin installing and eventually move to a waiting state. During this waiting state, a reload popup will show and ask the user to reload the page for new content. Until the user either clears the application cache or clicks the `reload` button on the popup, the service worker will continue serving the old content.
:::warning
Offline mode / precaching requires downloading all the static assets of the site ahead of time, and can consume unnecessary bandwidth. It may not be a good idea to activate it for all kind of sites.
:::
## Options {#options}
### `debug` {#debug}
- Type: `boolean`
- Default: `false`
Turn debug mode on:
- Workbox logs
- Additional Docusaurus logs
- Unoptimized SW file output
- Source maps
### `offlineModeActivationStrategies` {#offlinemodeactivationstrategies}
- Type: `('appInstalled' | 'mobile' | 'saveData'| 'queryString' | 'always')[]`
- Default: `['appInstalled', 'queryString', 'standalone']`
Strategies used to turn the offline mode on:
- `appInstalled`: activates for users having installed the site as an app (not 100% reliable)
- `standalone`: activates for users running the app as standalone (often the case once a PWA is installed)
- `queryString`: activates if queryString contains `offlineMode=true` (convenient for PWA debugging)
- `mobile`: activates for mobile users (`width <= 996px`)
- `saveData`: activates for users with `navigator.connection.saveData === true`
- `always`: activates for all users
:::warning
Use this carefully: some users may not like to be forced to use the offline mode.
:::
:::danger
It is not possible to detect if a page is rendered as a PWA in a reliable manner.
The `appinstalled` event has been [removed from the specification](https://github.com/w3c/manifest/pull/836), and the [`navigator.getInstalledRelatedApps()`](https://web.dev/get-installed-related-apps/) API is only supported in recent Chrome versions and require `related_applications` declared in the manifest.
The [`standalone` strategy](https://petelepage.com/blog/2019/07/is-my-pwa-installed/) is a nice fallback to activate the offline mode (at least when running the installed app).
:::
### `injectManifestConfig` {#injectmanifestconfig}
[Workbox options](https://developer.chrome.com/docs/workbox/reference/workbox-build/#type-InjectManifestOptions) to pass to `workbox.injectManifest()`. This gives you control over which assets will be precached, and be available offline.
- Type: `InjectManifestOptions`
- Default: `{}`
```js title="docusaurus.config.js"
export default {
plugins: [
[
'@docusaurus/plugin-pwa',
{
injectManifestConfig: {
manifestTransforms: [
//...
],
modifyURLPrefix: {
//...
},
// We already add regular static assets (HTML, images...) to be available offline
// You can add more files according to your needs
globPatterns: ['**/*.{pdf,docx,xlsx}'],
// ...
},
},
],
],
};
```
### `pwaHead` {#pwahead}
- Type: `({ tagName: string; [attributeName: string]: string })[]`
- Default: `[]`
Array of objects containing `tagName` and key-value pairs for attributes to inject into the `<head>` tag. Technically you can inject any head tag through this, but it's ideally used for tags to make your site PWA compliant. Here's a list of tag to make your app fully compliant:
```js
export default {
plugins: [
[
'@docusaurus/plugin-pwa',
{
pwaHead: [
{
tagName: 'link',
rel: 'icon',
href: '/img/docusaurus.png',
},
{
tagName: 'link',
rel: 'manifest',
href: '/manifest.json',
},
{
tagName: 'meta',
name: 'theme-color',
content: 'rgb(37, 194, 160)',
},
{
tagName: 'meta',
name: 'apple-mobile-web-app-capable',
content: 'yes',
},
{
tagName: 'meta',
name: 'apple-mobile-web-app-status-bar-style',
content: '#000',
},
{
tagName: 'link',
rel: 'apple-touch-icon',
href: '/img/docusaurus.png',
},
{
tagName: 'link',
rel: 'mask-icon',
href: '/img/docusaurus.svg',
color: 'rgb(37, 194, 160)',
},
{
tagName: 'meta',
name: 'msapplication-TileImage',
content: '/img/docusaurus.png',
},
{
tagName: 'meta',
name: 'msapplication-TileColor',
content: '#000',
},
],
},
],
],
};
```
### `swCustom` {#swcustom}
- Type: `string | undefined`
- Default: `undefined`
Useful for additional Workbox rules. You can do whatever a service worker can do here, and use the full power of workbox libraries. The code is transpiled, so you can use modern ES6+ syntax here.
For example, to cache files from external routes:
```js
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
// default fn export receiving some useful params
export default function swCustom(params) {
const {
debug, // :boolean
offlineMode, // :boolean
} = params;
// Cache responses from external resources
registerRoute((context) => {
return [
/graph\.facebook\.com\/.*\/picture/,
/netlify\.com\/img/,
/avatars1\.githubusercontent/,
].some((regex) => context.url.href.match(regex));
}, new StaleWhileRevalidate());
}
```
The module should have a `default` function export, and receives some params.
### `swRegister` {#swregister}
- Type: `string | false`
- Default: `'docusaurus-plugin-pwa/src/registerSW.js'`
Adds an entry before the Docusaurus app so that registration can happen before the app runs. The default `registerSW.js` file is enough for simple registration.
Passing `false` will disable registration entirely.
## Manifest example {#manifest-example}
The Docusaurus site manifest can serve as an inspiration:
```mdx-code-block
import CodeBlock from '@theme/CodeBlock';
<CodeBlock className="language-json">
{JSON.stringify(require('@site/static/manifest.json'),null,2)}
</CodeBlock>
```
## Customizing reload popup {#customizing-reload-popup}
The `@theme/PwaReloadPopup` component is rendered when a new service worker is waiting to be installed, and we suggest a reload to the user. You can [swizzle](../../swizzling.mdx) this component and implement your own UI. It will receive an `onReload` callback as props, which should be called when the `reload` button is clicked. This will tell the service worker to install the waiting service worker and reload the page.
The default theme includes an implementation for the reload popup and uses [Infima Alerts](https://infima.dev/docs/components/alert).
![A screen recording of the reload process. An alert box shows in the bottom right of the window, saying "New content available". After clicking the "Refresh" button, the page's main heading changes from "Introduction" to "PWA :))".](/img/pwa_reload.gif)
Your component can render `null`, but this is not recommended: users won't have a way to get up-to-date content.

View file

@ -0,0 +1,92 @@
---
sidebar_position: 10
slug: /api/plugins/@docusaurus/plugin-sitemap
---
# 📦 plugin-sitemap
import APITable from '@site/src/components/APITable';
This plugin creates sitemaps for your site so that search engine crawlers can crawl your site more accurately.
:::warning production only
This plugin is always inactive in development and **only active in production** because it works on the build output.
:::
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-sitemap
```
:::tip
If you use the preset `@docusaurus/preset-classic`, you don't need to install this plugin as a dependency.
You can configure this plugin through the [preset options](../../using-plugins.mdx#docusauruspreset-classic).
:::
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `lastmod` | `'date' \| 'datetime' \| null` | `null` | `date` is YYYY-MM-DD. `datetime` is a ISO 8601 datetime. `null` is disabled. See [sitemap docs](https://www.sitemaps.org/protocol.html#xmlTagDefinitions). |
| `changefreq` | `string \| null` | `'weekly'` | See [sitemap docs](https://www.sitemaps.org/protocol.html#xmlTagDefinitions) |
| `priority` | `number \| null` | `0.5` | See [sitemap docs](https://www.sitemaps.org/protocol.html#xmlTagDefinitions) |
| `ignorePatterns` | `string[]` | `[]` | A list of glob patterns; matching route paths will be filtered from the sitemap. Note that you may need to include the base URL in here. |
| `filename` | `string` | `sitemap.xml` | The path to the created sitemap file, relative to the output directory. Useful if you have two plugin instances outputting two files. |
```mdx-code-block
</APITable>
```
:::info
This plugin also respects some site config:
- [`noIndex`](../docusaurus.config.js.mdx#noIndex): results in no sitemap generated
- [`trailingSlash`](../docusaurus.config.js.mdx#trailingSlash): determines if the URLs in the sitemap have trailing slashes
:::
:::note About `lastmod`
The `lastmod` option will only output a sitemap `<lastmod>` tag if plugins provide [route metadata](../plugin-methods/lifecycle-apis.mdx#addRoute) attributes `sourceFilePath` and/or `lastUpdatedAt`.
All the official content plugins provide the metadata for routes backed by a content file (Markdown, MDX or React page components), but it is possible third-party plugin authors do not provide this information, and the plugin will not be able to output a `<lastmod>` tag for their routes.
:::
### Example configuration {#ex-config}
You can configure this plugin through preset options or plugin options.
:::tip
Most Docusaurus users configure this plugin through the preset options.
:::
```js config-tabs
// Preset Options: sitemap
// Plugin Options: @docusaurus/plugin-sitemap
const config = {
lastmod: 'date',
changefreq: 'weekly',
priority: 0.5,
ignorePatterns: ['/tags/**'],
filename: 'sitemap.xml',
};
```
You can find your sitemap at `/sitemap.xml`.

View file

@ -0,0 +1,57 @@
---
sidebar_position: 11
slug: /api/plugins/@docusaurus/plugin-vercel-analytics
---
# 📦 plugin-vercel-analytics
import APITable from '@site/src/components/APITable';
[Vercel Analytics](https://vercel.com/docs/analytics) provides comprehensive insights into your website's visitors, tracking top pages, referrers, and demographics like location, operating systems, and browser info.
:::warning production only
This plugin is always inactive in development and **only active in production** (`docusaurus build`) to avoid polluting the analytics statistics.
:::
## Installation {#installation}
```bash npm2yarn
npm install --save @docusaurus/plugin-vercel-analytics
```
## Configuration {#configuration}
Accepted fields:
```mdx-code-block
<APITable>
```
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `mode` | `string` | `'auto'` | Override the automatic environment detection. Read the [official docs](https://vercel.com/docs/analytics/package#mode) for details. |
| `debug` | `boolean` | `undefined` | Enable browser console logging of analytics events. Read the [official docs](https://vercel.com/docs/analytics/package#debug) for details. |
```mdx-code-block
</APITable>
```
### Example configuration {#ex-config}
You can configure this plugin through plugin options.
```js title="docusaurus.config.js"
export default {
plugins: [
[
'vercel-analytics',
{
debug: true,
mode: 'auto',
},
],
],
};
```