diff --git a/website/versioned_docs/version-2.0.0-rc.1/advanced/architecture.md b/website/versioned_docs/version-2.0.0-rc.1/advanced/architecture.md deleted file mode 100644 index 778b68eabd36..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/advanced/architecture.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -description: How Docusaurus works to build your app ---- - -# Architecture - -```mdx-code-block -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import Zoom from '@site/src/components/Zoom'; -``` - - - -![Architecture overview](/img/architecture.png) - - - -This diagram shows how Docusaurus works to build your app. Plugins each collect their content and emit JSON data; themes provide layout components which receive the JSON data as route modules. The bundler bundles all the components and emits a server bundle and a client bundle. - -Although you (either plugin authors or site creators) are writing JavaScript all the time, bear in mind that the JS is actually run in different environments: - -- All plugin lifecycle methods are run in Node. Therefore, until we support ES Modules in our codebase, plugin source code must be provided as CommonJS that can be `require`'d. -- The theme code is built with Webpack. They can be provided as ESM—following React conventions. - -Plugin code and theme code never directly import each other: they only communicate through protocols (in our case, through JSON temp files and calls to `addRoute`). A useful mental model is to imagine that the plugins are not written in JavaScript, but in another language like Rust. The only way to interact with plugins for the user is through `docusaurus.config.js`, which itself is run in Node (hence you can use `require` and pass callbacks as plugin options). - -During bundling, the config file itself is serialized and bundled, allowing the theme to access config options like `themeConfig` or `baseUrl` through [`useDocusaurusContext()`](../docusaurus-core.md#useDocusaurusContext). However, the `siteConfig` object only contains **serializable values** (values that are preserved after `JSON.stringify()`). Functions, regexes, etc. would be lost on the client side. The `themeConfig` is designed to be entirely serializable. diff --git a/website/versioned_docs/version-2.0.0-rc.1/advanced/client.md b/website/versioned_docs/version-2.0.0-rc.1/advanced/client.md deleted file mode 100644 index 6019e7328997..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/advanced/client.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -description: How the Docusaurus client is structured ---- - -# Client architecture - -## Theme aliases {#theme-aliases} - -A theme works by exporting a set of components, e.g. `Navbar`, `Layout`, `Footer`, to render the data passed down from plugins. Docusaurus and users use these components by importing them using the `@theme` webpack alias: - -```js -import Navbar from '@theme/Navbar'; -``` - -The alias `@theme` can refer to a few directories, in the following priority: - -1. A user's `website/src/theme` directory, which is a special directory that has the higher precedence. -2. A Docusaurus theme package's `theme` directory. -3. Fallback components provided by Docusaurus core (usually not needed). - -This is called a _layered architecture_: a higher-priority layer providing the component would shadow a lower-priority layer, making swizzling possible. Given the following structure: - -``` -website -├── node_modules -│ └── @docusaurus/theme-classic -│ └── theme -│ └── Navbar.js -└── src - └── theme - └── Navbar.js -``` - -`website/src/theme/Navbar.js` takes precedence whenever `@theme/Navbar` is imported. This behavior is called component swizzling. If you are familiar with Objective C where a function's implementation can be swapped during runtime, it's the exact same concept here with changing the target `@theme/Navbar` is pointing to! - -We already talked about how the "userland theme" in `src/theme` can re-use a theme component through the [`@theme-original`](#wrapping) alias. One theme package can also wrap a component from another theme, by importing the component from the initial theme, using the `@theme-init` import. - -Here's an example of using this feature to enhance the default theme `CodeBlock` component with a `react-live` playground feature. - -```js -import InitialCodeBlock from '@theme-init/CodeBlock'; -import React from 'react'; - -export default function CodeBlock(props) { - return props.live ? ( - - ) : ( - - ); -} -``` - -Check the code of `@docusaurus/theme-live-codeblock` for details. - -:::caution - -Unless you want to publish a re-usable "theme enhancer" (like `@docusaurus/theme-live-codeblock`), you likely don't need `@theme-init`. - -::: - -It can be quite hard to wrap your mind around these aliases. Let's imagine the following case with a super convoluted setup with three themes/plugins and the site itself all trying to define the same component. Internally, Docusaurus loads these themes as a "stack". - -```text -+-------------------------------------------------+ -| `website/src/theme/CodeBlock.js` | <-- `@theme/CodeBlock` always points to the top -+-------------------------------------------------+ -| `theme-live-codeblock/theme/CodeBlock/index.js` | <-- `@theme-original/CodeBlock` points to the topmost non-swizzled component -+-------------------------------------------------+ -| `plugin-awesome-codeblock/theme/CodeBlock.js` | -+-------------------------------------------------+ -| `theme-classic/theme/CodeBlock/index.js` | <-- `@theme-init/CodeBlock` always points to the bottom -+-------------------------------------------------+ -``` - -The components in this "stack" are pushed in the order of `preset plugins > preset themes > plugins > themes > site`, so the swizzled component in `website/src/theme` always comes out on top because it's loaded last. - -`@theme/*` always points to the topmost component—when `CodeBlock` is swizzled, all other components requesting `@theme/CodeBlock` receive the swizzled version. - -`@theme-original/*` always points to the topmost non-swizzled component. That's why you can import `@theme-original/CodeBlock` in the swizzled component—it points to the next one in the "component stack", a theme-provided one. Plugin authors should not try to use this because your component could be the topmost component and cause a self-import. - -`@theme-init/*` always points to the bottommost component—usually, this comes from the theme or plugin that first provides this component. Individual plugins / themes trying to enhance code block can safely use `@theme-init/CodeBlock` to get its basic version. Site creators should generally not use this because you likely want to enhance the _topmost_ instead of the _bottommost_ component. It's also possible that the `@theme-init/CodeBlock` alias does not exist at all—Docusaurus only creates it when it points to a different one from `@theme-original/CodeBlock`, i.e. when it's provided by more than one theme. We don't waste aliases! - -## Client modules {#client-modules} - -Client modules are part of your site's bundle, just like theme components. However, they are usually side-effect-ful. Client modules are anything that can be `import`ed by Webpack—CSS, JS, etc. JS scripts usually work on the global context, like registering event listeners, creating global variables... - -These modules are imported globally before React even renders the initial UI. - -```js title="@docusaurus/core/App.tsx" -// How it works under the hood -import '@generated/client-modules'; -``` - -Plugins and sites can both declare client modules, through [`getClientModules`](../api/plugin-methods/lifecycle-apis.md#getClientModules) and [`siteConfig.clientModules`](../api/docusaurus.config.js.md#clientModules), respectively. - -Client modules are called during server-side rendering as well, so remember to check the [execution environment](./ssg.md#escape-hatches) before accessing client-side globals. - -```js title="mySiteGlobalJs.js" -import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; - -if (ExecutionEnvironment.canUseDOM) { - // As soon as the site loads in the browser, register a global event listener - window.addEventListener('keydown', (e) => { - if (e.code === 'Period') { - location.assign(location.href.replace('.com', '.dev')); - } - }); -} -``` - -CSS stylesheets imported as client modules are [global](../styling-layout.md#global-styles). - -```css title="mySiteGlobalCss.css" -/* This stylesheet is global. */ -.globalSelector { - color: red; -} -``` - -### Client module lifecycles {#client-module-lifecycles} - -Besides introducing side-effects, client modules can optionally export two lifecycle functions: `onRouteUpdate` and `onRouteDidUpdate`. - -Because Docusaurus builds a single-page application, `script` tags will only be executed the first time the page loads, but will not re-execute on page transitions. These lifecycles are useful if you have some imperative JS logic that should execute every time a new page has loaded, e.g., to manipulate DOM elements, to send analytics data, etc. - -For every route transition, there will be several important timings: - -1. The user clicks a link, which causes the router to change its current location. -2. Docusaurus preloads the next route's assets, while keeping displaying the current page's content. -3. The next route's assets have loaded. -4. The new location's route component gets rendered to DOM. - -`onRouteUpdate` will be called at event (2), and `onRouteDidUpdate` will be called at (4). They both receive the current location and the previous location (which can be `null`, if this is the first screen). - -`onRouteUpdate` can optionally return a "cleanup" callback, which will be called at (3). For example, if you want to display a progress bar, you can start a timeout in `onRouteUpdate`, and clear the timeout in the callback. (The classic theme already provides an `nprogress` integration this way.) - -Note that the new page's DOM is only available during event (4). If you need to manipulate the new page's DOM, you'll likely want to use `onRouteDidUpdate`, which will be fired as soon as the DOM on the new page has mounted. - -```js title="myClientModule.js" -import type {Location} from 'history'; - -export function onRouteDidUpdate({location, previousLocation}) { - // Don't execute if we are still on the same page; the lifecycle may be fired - // because the hash changes (e.g. when navigating between headings) - if (location.pathname !== previousLocation?.pathname) { - const title = document.getElementsByTagName('h1')[0]; - if (title) { - title.innerText += '❤️'; - } - } -} - -export function onRouteUpdate({location, previousLocation}) { - if (location.pathname !== previousLocation?.pathname) { - const progressBarTimeout = window.setTimeout(() => { - nprogress.start(); - }, delay); - return () => window.clearTimeout(progressBarTimeout); - } - return undefined; -} -``` - -Or, if you are using TypeScript and you want to leverage contextual typing: - -```ts title="myClientModule.ts" -import type {ClientModule} from '@docusaurus/types'; - -const module: ClientModule = { - onRouteUpdate({location, previousLocation}) { - // ... - }, - onRouteDidUpdate({location, previousLocation}) { - // ... - }, -}; -export default module; -``` - -Both lifecycles will fire on first render, but they will not fire on server-side, so you can safely access browser globals in them. - -:::tip Prefer using React - -Client module lifecycles are purely imperative, and you can't use React hooks or access React contexts within them. If your operations are state-driven or involve complicated DOM manipulations, you should consider [swizzling components](../swizzling.md) instead. - -::: diff --git a/website/versioned_docs/version-2.0.0-rc.1/advanced/index.md b/website/versioned_docs/version-2.0.0-rc.1/advanced/index.md deleted file mode 100644 index afe7f1a57050..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/advanced/index.md +++ /dev/null @@ -1,12 +0,0 @@ -# Advanced Tutorials - -This section is not going to be very structured, but we will cover the following topics: - -```mdx-code-block -import DocCardList from '@theme/DocCardList'; -import {useCurrentSidebarCategory} from '@docusaurus/theme-common'; - - -``` - -We will assume that you have finished the guides, and know the basics like how to configure plugins, how to write React components, etc. These sections will have plugin authors and code contributors in mind, so we may occasionally refer to [plugin APIs](../api/plugin-methods/README.md) or other architecture details. Don't panic if you don't understand everything😉 diff --git a/website/versioned_docs/version-2.0.0-rc.1/advanced/plugins.md b/website/versioned_docs/version-2.0.0-rc.1/advanced/plugins.md deleted file mode 100644 index 29910ff0e2f9..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/advanced/plugins.md +++ /dev/null @@ -1,129 +0,0 @@ -# Plugins - -Plugins are the building blocks of features in a Docusaurus 2 site. Each plugin handles its own individual feature. Plugins may work and be distributed as part of a bundle via presets. - -## Creating plugins {#creating-plugins} - -A plugin is a function that takes two parameters: `context` and `options`. It returns a plugin instance object (or a promise). You can create plugins as functions or modules. For more information, refer to the [plugin method references section](../api/plugin-methods/README.md). - -### Function definition {#function-definition} - -You can use a plugin as a function directly included in the Docusaurus config file: - -```js title="docusaurus.config.js" -module.exports = { - // ... - plugins: [ - // highlight-start - async function myPlugin(context, options) { - // ... - return { - name: 'my-plugin', - async loadContent() { - // ... - }, - async contentLoaded({content, actions}) { - // ... - }, - /* other lifecycle API */ - }; - }, - // highlight-end - ], -}; -``` - -### Module definition {#module-definition} - -You can use a plugin as a module path referencing a separate file or npm package: - -```js title="docusaurus.config.js" -module.exports = { - // ... - plugins: [ - // without options: - './my-plugin', - // or with options: - ['./my-plugin', options], - ], -}; -``` - -Then in the folder `my-plugin`, you can create an `index.js` such as this: - -```js title="my-plugin/index.js" -module.exports = async function myPlugin(context, options) { - // ... - return { - name: 'my-plugin', - async loadContent() { - /* ... */ - }, - async contentLoaded({content, actions}) { - /* ... */ - }, - /* other lifecycle API */ - }; -}; -``` - ---- - -You can view all plugins installed in your site using the [debug plugin's metadata panel](/__docusaurus/debug/metadata). - -Plugins come as several types: - -- `package`: an external package you installed -- `project`: a plugin you created in your project, given to Docusaurus as a local file path -- `local`: a plugin created using the function definition -- `synthetic`: a "fake plugin" Docusaurus created internally, so we take advantage of our modular architecture and don't let the core do much special work. You won't see this in the metadata because it's an implementation detail. - -You can access them on the client side with `useDocusaurusContext().siteMetadata.pluginVersions`. - -## Plugin design {#plugin-design} - -Docusaurus' implementation of the plugins system provides us with a convenient way to hook into the website's lifecycle to modify what goes on during development/build, which involves (but is not limited to) extending the webpack config, modifying the data loaded, and creating new components to be used in a page. - -### Theme design {#theme-design} - -When plugins have loaded their content, the data is made available to the client side through actions like [`createData` + `addRoute`](../api/plugin-methods/lifecycle-apis.md#addRoute) or [`setGlobalData`](../api/plugin-methods/lifecycle-apis.md#setGlobalData). This data has to be _serialized_ to plain strings, because [plugins and themes run in different environments](./architecture.md). Once the data arrives on the client side, the rest becomes familiar to React developers: data is passed along components, components are bundled with Webpack, and rendered to the window through `ReactDOM.render`... - -**Themes provide the set of UI components to render the content.** Most content plugins need to be paired with a theme in order to be actually useful. The UI is a separate layer from the data schema, which makes swapping designs easy. - -For example, a Docusaurus blog may consist of a blog plugin and a blog theme. - -:::note - -This is a contrived example: in practice, `@docusaurus/theme-classic` provides the theme for docs, blog, and layouts. - -::: - -```js title="docusaurus.config.js" -module.exports = { - // highlight-next-line - themes: ['theme-blog'], - plugins: ['plugin-content-blog'], -}; -``` - -And if you want to use Bootstrap styling, you can swap out the theme with `theme-blog-bootstrap` (another fictitious non-existing theme): - -```js title="docusaurus.config.js" -module.exports = { - // highlight-next-line - themes: ['theme-blog-bootstrap'], - plugins: ['plugin-content-blog'], -}; -``` - -Now, although the theme receives the same data from the plugin, how the theme chooses to _render_ the data as UI can be drastically different. - -While themes share the exact same lifecycle methods with plugins, themes' implementations can look very different from those of plugins based on themes' designed objectives. - -Themes are designed to complete the build of your Docusaurus site and supply the components used by your site, plugins, and the themes themselves. A theme still acts like a plugin and exposes some lifecycle methods, but most likely they would not use [`loadContent`](../api/plugin-methods/lifecycle-apis.md#loadContent), since they only receive data from plugins, but don't generate data themselves; themes are typically also accompanied by an `src/theme` directory full of components, which are made known to the core through the [`getThemePath`](../api/plugin-methods/extend-infrastructure.md#getThemePath) lifecycle. - -To summarize: - -- Themes share the same lifecycle methods with Plugins -- Themes are run after all existing Plugins -- Themes add component aliases by providing `getThemePath`. diff --git a/website/versioned_docs/version-2.0.0-rc.1/advanced/routing.md b/website/versioned_docs/version-2.0.0-rc.1/advanced/routing.md deleted file mode 100644 index 9ee8294b1b1a..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/advanced/routing.md +++ /dev/null @@ -1,279 +0,0 @@ ---- -description: "Docusaurus' routing system follows single-page application conventions: one route, one component." ---- - -# Routing - -```mdx-code-block -import Link from '@docusaurus/Link'; -import {useLatestVersion, useActiveDocContext} from '@docusaurus/plugin-content-docs/client'; -import {useLocation} from '@docusaurus/router'; -import BrowserWindow from '@site/src/components/BrowserWindow'; -``` - -Docusaurus' routing system follows single-page application conventions: one route, one component. In this section, we will begin by talking about routing within the three content plugins (docs, blog, and pages), and then go beyond to talk about the underlying routing system. - -## Routing in content plugins {#routing-in-content-plugins} - -Every content plugin provides a `routeBasePath` option. It defines where the plugins append their routes to. By default, the docs plugin puts its routes under `/docs`; the blog plugin, `/blog`; and the pages plugin, `/`. You can think about the route structure like this: - -![plugin routes model](/img/routes.png#gh-light-mode-only)![plugin routes model](/img/routes-dark.png#gh-dark-mode-only) - -Any route will be matched against this nested route config until a good match is found. For example, when given a route `/docs/configuration`, Docusaurus first enters the `/docs` branch, and then searches among the subroutes created by the docs plugin. - -Changing `routeBasePath` can effectively alter your site's route structure. For example, in [Docs-only mode](../guides/docs/docs-introduction.md#docs-only-mode), we mentioned that configuring `routeBasePath: '/'` for docs means that all routes that the docs plugin create would not have the `/docs` prefix, yet it doesn't prevent you from having more subroutes like `/blog` created by other plugins. - -Next, let's look at how the three plugins structure their own "boxes of subroutes". - -### Pages routing {#pages-routing} - -Pages routing are straightforward: the file paths directly map to URLs, without any other way to customize. See the [pages docs](../guides/creating-pages.md#routing) for more information. - -The component used for Markdown pages is `@theme/MDXPage`. React pages are directly used as the route's component. - -### Blog routing {#blog-routing} - -The blog creates the following routes: - -- **Posts list pages**: `/`, `/page/2`, `/page/3`... - - The component is `@theme/BlogListPage`. -- **Post pages**: `/2021/11/21/algolia-docsearch-migration`, `/2021/05/12/announcing-docusaurus-two-beta`... - - Generated from each Markdown post. - - The routes are fully customizable through the `slug` front matter. - - The component is `@theme/BlogPostPage`. -- **Tags list page**: `/tags` - - The route is customizable through the `tagsBasePath` option. - - The component is `@theme/BlogTagsListPage`. -- **Tag pages**: `/tags/adoption`, `/tags/beta`... - - Generated through the tags defined in each post's front matter. - - The routes always have base defined in `tagsBasePath`, but the subroutes are customizable through the tag's `permalink` field. - - The component is `@theme/BlogTagsPostsPage`. -- **Archive page**: `/archive` - - The route is customizable through the `archiveBasePath` option. - - The component is `@theme/BlogArchivePage`. - -### Docs routing {#docs-routing} - -The docs is the only plugin that creates **nested routes**. At the top, it registers [**version paths**](../guides/docs/versioning.md): `/`, `/next`, `/2.0.0-beta.13`... which provide the version context, including the layout and sidebar. This ensures that when switching between individual docs, the sidebar's state is preserved, and that you can switch between versions through the navbar dropdown while staying on the same doc. The component used is `@theme/DocPage`. - -```mdx-code-block -export const URLPath = () => {useLocation().pathname}; - -export const FilePath = () => { - const currentVersion = useActiveDocContext('default').activeVersion.name; - return {currentVersion === 'current' ? './docs/' : `./versioned_docs/version-${currentVersion}/`}advanced/routing.md; -} -``` - -The individual docs are rendered in the remaining space after the navbar, footer, sidebar, etc. have all been provided by the `DocPage` component. For example, this page, , is generated from the file at . The component used is `@theme/DocItem`. - -The doc's `slug` front matter customizes the last part of the route, but the base route is always defined by the plugin's `routeBasePath` and the version's `path`. - -### File paths and URL paths {#file-paths-and-url-paths} - -Throughout the documentation, we always try to be unambiguous about whether we are talking about file paths or URL paths. Content plugins usually map file paths directly to URL paths, for example, `./docs/advanced/routing.md` will become `/docs/advanced/routing`. However, with `slug`, you can make URLs totally decoupled from the file structure. - -When writing links in Markdown, you could either mean a _file path_, or a _URL path_, which Docusaurus would use several heuristics to determine. - -- If the path has a `@site` prefix, it is _always_ an asset file path. -- If the path has an `http(s)://` prefix, it is _always_ a URL path. -- If the path doesn't have an extension, it is a URL path. For example, a link `[page](../plugins)` on a page with URL `/docs/advanced/routing` will link to `/docs/plugins`. Docusaurus will only detect broken links when building your site (when it knows the full route structure), but will make no assumptions about the existence of a file. It is exactly equivalent to writing `page` in a JSX file. -- If the path has an `.md(x)` extension, Docusaurus would try to resolve that Markdown file to a URL, and replace the file path with a URL path. -- If the path has any other extension, Docusaurus would treat it as [an asset](../guides/markdown-features/markdown-features-assets.mdx) and bundle it. - -The following directory structure may help you visualize this file → URL mapping. Assume that there's no slug customization in any page. - -
- -A sample site structure - -```bash -. -├── blog # blog plugin has routeBasePath: '/blog' -│ ├── 2019-05-28-first-blog-post.md # -> /blog/2019/05/28/first-blog-post -│ ├── 2019-05-29-long-blog-post.md # -> /blog/2019/05/29/long-blog-post -│ ├── 2021-08-01-mdx-blog-post.mdx # -> /blog/2021/08/01/mdx-blog-post -│ └── 2021-08-26-welcome -│ ├── docusaurus-plushie-banner.jpeg -│ └── index.md # -> /blog/2021/08/26/welcome -├── docs # docs plugin has routeBasePath: '/docs'; current version has base path '/' -│ ├── intro.md # -> /docs/intro -│ ├── tutorial-basics -│ │ ├── _category_.json -│ │ ├── congratulations.md # -> /docs/tutorial-basics/congratulations -│ │ └── markdown-features.mdx # -> /docs/tutorial-basics/congratulations -│ └── tutorial-extras -│ ├── _category_.json -│ ├── manage-docs-versions.md # -> /docs/tutorial-extras/manage-docs-versions -│ └── translate-your-site.md # -> /docs/tutorial-extras/translate-your-site -├── src -│ └── pages # pages plugin has routeBasePath: '/' -│ ├── index.module.css -│ ├── index.tsx # -> / -│ └── markdown-page.md # -> /markdown-page -└── versioned_docs - └── version-1.0.0 # version has base path '/1.0.0' - ├── intro.md # -> /docs/1.0.0/intro - ├── tutorial-basics - │ ├── _category_.json - │ ├── congratulations.md # -> /docs/1.0.0/tutorial-basics/congratulations - │ └── markdown-features.mdx # -> /docs/1.0.0/tutorial-basics/congratulations - └── tutorial-extras - ├── _category_.json - ├── manage-docs-versions.md # -> /docs/1.0.0/tutorial-extras/manage-docs-versions - └── translate-your-site.md # -> /docs/1.0.0/tutorial-extras/translate-your-site -``` - -
- -So much about content plugins. Let's take one step back and talk about how routing works in a Docusaurus app in general. - -## Routes become HTML files {#routes-become-html-files} - -Because Docusaurus is a server-side rendering framework, all routes generated will be server-side rendered into static HTML files. If you are familiar with the behavior of HTTP servers like [Apache2](https://httpd.apache.org/docs/trunk/getting-started.html), you will understand how this is done: when the browser sends a request to the route `/docs/advanced/routing`, the server interprets that as request for the HTML file `/docs/advanced/routing/index.html`, and returns that. - -The `/docs/advanced/routing` route can correspond to either `/docs/advanced/routing/index.html` or `/docs/advanced/routing.html`. Some hosting providers differentiate between them using the presence of a trailing slash, and may or may not tolerate the other. Read more in the [trailing slash guide](https://github.com/slorber/trailing-slash-guide). - -For example, the build output of the directory above is (ignoring other assets and JS bundle): - -
- -Output of the above workspace - -```bash -build -├── 404.html # /404/ -├── blog -│ ├── archive -│ │ └── index.html # /blog/archive/ -│ ├── first-blog-post -│ │ └── index.html # /blog/first-blog-post/ -│ ├── index.html # /blog/ -│ ├── long-blog-post -│ │ └── index.html # /blog/long-blog-post/ -│ ├── mdx-blog-post -│ │ └── index.html # /blog/mdx-blog-post/ -│ ├── tags -│ │ ├── docusaurus -│ │ │ └── index.html # /blog/tags/docusaurus/ -│ │ ├── hola -│ │ │ └── index.html # /blog/tags/hola/ -│ │ └── index.html # /blog/tags/ -│ └── welcome -│ └── index.html # /blog/welcome/ -├── docs -│ ├── 1.0.0 -│ │ ├── intro -│ │ │ └── index.html # /docs/1.0.0/intro/ -│ │ ├── tutorial-basics -│ │ │ ├── congratulations -│ │ │ │ └── index.html # /docs/1.0.0/tutorial-basics/congratulations/ -│ │ │ └── markdown-features -│ │ │ └── index.html # /docs/1.0.0/tutorial-basics/markdown-features/ -│ │ └── tutorial-extras -│ │ ├── manage-docs-versions -│ │ │ └── index.html # /docs/1.0.0/tutorial-extras/manage-docs-versions/ -│ │ └── translate-your-site -│ │ └── index.html # /docs/1.0.0/tutorial-extras/translate-your-site/ -│ ├── intro -│ │ └── index.html # /docs/1.0.0/intro/ -│ ├── tutorial-basics -│ │ ├── congratulations -│ │ │ └── index.html # /docs/tutorial-basics/congratulations/ -│ │ └── markdown-features -│ │ └── index.html # /docs/tutorial-basics/markdown-features/ -│ └── tutorial-extras -│ ├── manage-docs-versions -│ │ └── index.html # /docs/tutorial-extras/manage-docs-versions/ -│ └── translate-your-site -│ └── index.html # /docs/tutorial-extras/translate-your-site/ -├── index.html # / -└── markdown-page - └── index.html # /markdown-page/ -``` - -
- -If `trailingSlash` is set to `false`, the build would emit `intro.html` instead of `intro/index.html`. - -All HTML files will reference its JS assets using absolute URLs, so in order for the correct assets to be located, you have to configure the `baseUrl` field. Note that `baseUrl` doesn't affect the emitted bundle's file structure: the base URL is one level above the Docusaurus routing system. You can see the aggregate of `url` and `baseUrl` as the actual location of your Docusaurus site. - -For example, the emitted HTML would contain links like ``. Because absolute URLs are resolved from the host, if the bundle placed under the path `https://example.com/base/`, the link will point to `https://example.com/assets/js/runtime~main.7ed5108a.js`, which is, well, non-existent. By specifying `/base/` as base URL, the link will correctly point to `/base/assets/js/runtime~main.7ed5108a.js`. - -Localized sites have the locale as part of the base URL as well. For example, `https://docusaurus.io/zh-CN/docs/advanced/routing/` has base URL `/zh-CN/`. - -## Generating and accessing routes {#generating-and-accessing-routes} - -The `addRoute` lifecycle action is used to generate routes. It registers a piece of route config to the route tree, giving a route, a component, and props that the component needs. The props and the component are both provided as paths for the bundler to `require`, because as explained in the [architecture overview](architecture.md), server and client only communicate through temp files. - -All routes are aggregated in `.docusaurus/routes.js`, which you can view with the debug plugin's [routes panel](/__docusaurus/debug/routes). - -On the client side, we offer `@docusaurus/router` to access the page's route. `@docusaurus/router` is a re-export of the [`react-router-dom`](https://www.npmjs.com/package/react-router-dom/v/5.3.0) package. For example, you can use `useLocation` to get the current page's [location](https://developer.mozilla.org/en-US/docs/Web/API/Location), and `useHistory` to access the [history object](https://developer.mozilla.org/en-US/docs/Web/API/History). (They are not the same as the browser API, although similar in functionality. Refer to the React Router documentation for specific APIs.) - -This API is **SSR safe**, as opposed to the browser-only `window.location`. - -```jsx title="myComponent.js" -import React from 'react'; -import {useLocation} from '@docusaurus/router'; - -export function PageRoute() { - // React router provides the current component's route, even in SSR - const location = useLocation(); - return ( - - We are currently on {location.pathname} - - ); -} -``` - -```mdx-code-block -export function PageRoute() { - const location = useLocation(); - return ( - - We are currently on {location.pathname} - - ); -} - - - - - - -``` - -## Escaping from SPA redirects {#escaping-from-spa-redirects} - -Docusaurus builds a [single-page application](https://developer.mozilla.org/en-US/docs/Glossary/SPA), where route transitions are done through the `history.push()` method of React router. This operation is done on the client side. However, the prerequisite for a route transition to happen this way is that the target URL is known to our router. Otherwise, the router catches this path and displays a 404 page instead. - -If you put some HTML pages under the `static` folder, they will be copied to the build output and therefore become accessible as part of your website, yet it's not part of the Docusaurus route system. We provide a `pathname://` protocol that allows you to redirect to another part of your domain in a non-SPA fashion, as if this route is an external link. Try the following two links: - -```md -- [/pure-html](/pure-html) -- [pathname:///pure-html](pathname:///pure-html) -``` - - - -- [/pure-html](/pure-html) -- [pathname:///pure-html](pathname:///pure-html) - - - -:::tip - -The first link will **not** trigger a "broken links detected" check during the production build, because the respective file actually exists. Nevertheless, when you click on the link, a "page not found" will be displayed until you refresh. - -::: - -The `pathname://` protocol is useful for referencing any content in the static folder. For example, Docusaurus would convert [all Markdown static assets to require() calls](../guides/markdown-features/markdown-features-assets.mdx#static-assets). You can use `pathname://` to keep it a regular link instead of being hashed by Webpack. - -```md title="my-doc.md" -![An image from the static](pathname:///img/docusaurus.png) - -[An asset from the static](pathname:///files/asset.pdf) -``` - -Docusaurus will only strip the `pathname://` prefix without processing the content. diff --git a/website/versioned_docs/version-2.0.0-rc.1/advanced/ssg.md b/website/versioned_docs/version-2.0.0-rc.1/advanced/ssg.md deleted file mode 100644 index 09fb981e6dfc..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/advanced/ssg.md +++ /dev/null @@ -1,217 +0,0 @@ ---- -sidebar_label: Static site generation -description: Docusaurus statically renders your React code into HTML, allowing faster load speed and better SEO. ---- - -# Static site generation (SSG) - -In [architecture](architecture.md), we mentioned that the theme is run in Webpack. But beware: that doesn't mean it always has access to browser globals! The theme is built twice: - -- During **server-side rendering**, the theme is compiled in a sandbox called [React DOM Server](https://reactjs.org/docs/react-dom-server.html). You can see this as a "headless browser", where there is no `window` or `document`, only React. SSR produces static HTML pages. -- During **client-side rendering**, the theme is compiled to JavaScript that gets eventually executed in the browser, so it has access to browser variables. - -:::info SSR or SSG? - -_Server-side rendering_ and _static site generation_ can be different concepts, but we use them interchangeably. - -Strictly speaking, Docusaurus is a static site generator, because there's no server-side runtime—we statically render to HTML files that are deployed on a CDN, instead of dynamically pre-rendering on each request. This differs from the working model of [Next.js](https://nextjs.org/). - -::: - -Therefore, while you probably know not to access Node globals like `process` ([or can we?](#node-env)) or the `'fs'` module, you can't freely access browser globals either. - -```jsx -import React from 'react'; - -export default function WhereAmI() { - return {window.location.href}; -} -``` - -This looks like idiomatic React, but if you run `docusaurus build`, you will get an error: - -``` -ReferenceError: window is not defined -``` - -This is because during server-side rendering, the Docusaurus app isn't actually run in browser, and it doesn't know what `window` is. - -```mdx-code-block -
-What about process.env.NODE_ENV? -``` - -One exception to the "no Node globals" rule is `process.env.NODE_ENV`. In fact, you can use it in React, because Webpack injects this variable as a global: - -```jsx -import React from 'react'; - -export default function expensiveComp() { - if (process.env.NODE_ENV === 'development') { - return <>This component is not shown in development; - } - const res = someExpensiveOperationThatLastsALongTime(); - return <>{res}; -} -``` - -During Webpack build, the `process.env.NODE_ENV` will be replaced with the value, either `'development'` or `'production'`. You will then get different build results after dead code elimination: - -import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; - -```mdx-code-block - - -``` - -```diff -import React from 'react'; - -export default function expensiveComp() { - // highlight-next-line - if ('development' === 'development') { -+ return <>This component is not shown in development; - } -- const res = someExpensiveOperationThatLastsALongTime(); -- return <>{res}; -} -``` - -```mdx-code-block - - -``` - -```diff -import React from 'react'; - -export default function expensiveComp() { - // highlight-next-line -- if ('production' === 'development') { -- return <>This component is not shown in development; -- } -+ const res = someExpensiveOperationThatLastsALongTime(); -+ return <>{res}; -} -``` - -```mdx-code-block - - -
-``` - -## Understanding SSR {#understanding-ssr} - -React is not just a dynamic UI runtime—it's also a templating engine. Because Docusaurus sites mostly contain static contents, it should be able to work without any JavaScript (which React runs in), but only plain HTML/CSS. And that's what server-side rendering offers: statically rendering your React code into HTML, without any dynamic content. An HTML file has no concept of client state (it's purely markup), hence it shouldn't rely on browser APIs. - -These HTML files are the first to arrive at the user's browser screen when a URL is visited (see [routing](routing.md)). Afterwards, the browser fetches and runs other JS code to provide the "dynamic" parts of your site—anything implemented with JavaScript. However, before that, the main content of your page is already visible, allowing faster loading. - -In CSR-only apps, all DOM elements are generated on client side with React, and the HTML file only ever contains one root element for React to mount DOM to; in SSR, React is already facing a fully built HTML page, and it only needs to correlate the DOM elements with the virtual DOM in its model. This step is called "hydration". After React has hydrated the static markup, the app starts to work as any normal React app. - -Note that Docusaurus is ultimately a single-page application, so static site generation is only an optimization (_progressive enhancement_, as it's called), but our functionality does not fully depend on those HTML files. This is contrary to site generators like [Jekyll](https://jekyllrb.com/) and [Docusaurus v1](https://v1.docusaurus.io/), where all files are statically transformed to markup, and interactiveness is added through external JavaScript linked with ` - <% }); %> - <%~ it.postBodyTags %> - -`, -}; -``` - -### `titleDelimiter` {#titleDelimiter} - -- Type: `string` - -Will be used as title delimiter in the generated `` tag. - -Example: - -```js title="docusaurus.config.js" -module.exports = { - titleDelimiter: '🦖', // Defaults to `|` -}; -``` - -### `baseUrlIssueBanner` {#baseUrlIssueBanner} - -- Type: `boolean` - -When enabled, will show a banner in case your site can't load its CSS or JavaScript files, which is a very common issue, often related to a wrong `baseUrl` in site config. - -Example: - -```js title="docusaurus.config.js" -module.exports = { - baseUrlIssueBanner: true, // Defaults to `true` -}; -``` - -![baseUrlIssueBanner](/img/baseUrlIssueBanner.png) - -:::caution - -This banner needs to inline CSS / JS in case all asset loading fails due to wrong base URL. - -If you have a strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), you should rather disable it. - -::: diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/misc/_category_.yml b/website/versioned_docs/version-2.0.0-rc.1/api/misc/_category_.yml deleted file mode 100644 index 2fb307376467..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/misc/_category_.yml +++ /dev/null @@ -1,2 +0,0 @@ -label: Miscellaneous -position: 4 diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/misc/create-docusaurus.md b/website/versioned_docs/version-2.0.0-rc.1/api/misc/create-docusaurus.md deleted file mode 100644 index b4dc0491e4a8..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/misc/create-docusaurus.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -sidebar_position: 0 -slug: /api/misc/create-docusaurus ---- - -# 📦 create-docusaurus - -A scaffolding utility to help you instantly set up a functional Docusaurus app. - -## Usage {#usage} - -```bash -npx create-docusaurus@latest [name] [template] [rootDir] -``` - -The `name` argument will be used as the site's path as well as the `name` field in the created app's package.json. It can be an absolute path, or a path relative to `rootDir`. - -The `template` argument can be one of the following: - -- `classic`: Uses the classic template (recommended) -- `facebook`: Uses the Facebook/Meta template, which contains some Meta-specific setup -- A git repo URL (beginning with `https://` or `git@`), which can be cloned to the destination -- A local file path relative to CWD, which contains the files to be copied to destination - -The `rootDir` will be used to resolve the absolute path to the site directory. The default is CWD. - -:::caution - -This command should be preferably used in an interactive shell so all features are available. - -::: - -## Options {#options} - -### `-t, --typescript` {#typescript} - -Used when the template argument is a recognized name. Currently, only `classic` provides a TypeScript variant. - -### `-g, --git-strategy` {#git-strategy} - -Used when the template argument is a git repo. It needs to be one of: - -- `deep`: preserves full git history -- `shallow`: clones with `--depth=1` -- `copy`: does a shallow clone, but does not create a git repo -- `custom`: enter your custom git clone command. We will prompt you for it. You can write something like `git clone --depth 10`, and we will append the repository URL and destination directory. - -### `-p, --package-manager` {#package-manager} - -Value should be one of `npm`, `yarn`, or `pnpm`. If it's not explicitly provided, Docusaurus will infer one based on: - -- The lockfile already present in the CWD (e.g. if you are setting up website in an existing project) -- The command used to invoke `create-docusaurus` (e.g. `npm init`, `npx`, `yarn create`, etc.) -- Interactive prompting, in case all heuristics are not present - -### `-s, --skip-install` {#skip-install} - -If provided, Docusaurus will not automatically install dependencies after creating the app. The `--package-manager` option is only useful when you are actually installing dependencies. diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/misc/eslint-plugin/README.md b/website/versioned_docs/version-2.0.0-rc.1/api/misc/eslint-plugin/README.md deleted file mode 100644 index 9d0d2236846c..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/misc/eslint-plugin/README.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -sidebar_position: 1 -slug: /api/misc/@docusaurus/eslint-plugin ---- - -# 📦 eslint-plugin - -[ESLint](https://eslint.org/) is a tool that statically analyzes your code and reports problems or suggests best practices through editor hints and command line. Docusaurus provides an ESLint plugin to enforce best Docusaurus practices. - -## Installation - -```bash npm2yarn -npm install --save-dev @docusaurus/eslint-plugin -``` - -## Usage - -Add `@docusaurus` to the plugins section of your `.eslintrc` configuration file: - -```json title=".eslintrc" -{ - "plugins": ["@docusaurus"] -} -``` - -Then, you can extend one of the configs (e.g. the `recommended` config): - -```json title=".eslintrc" -{ - "extends": ["plugin:@docusaurus/recommended"] -} -``` - -Each config contains a set of rules. For more fine-grained control, you can also configure the rules you want to use directly: - -```json title=".eslintrc" -{ - "rules": { - "@docusaurus/string-literal-i18n-messages": "error", - "@docusaurus/no-untranslated-text": "warn" - } -} -``` - -## Supported Configs - -- Recommended: recommended rule set for most Docusaurus sites that should be extended from. -- All: **all** rules enabled. This will change between minor versions, so you should not use this if you want to avoid unexpected breaking changes. - -## Supported Rules - -| Name | Description | | -| --- | --- | --- | -| [`@docusaurus/no-untranslated-text`](./no-untranslated-text.md) | Enforce text labels in JSX to be wrapped by translate calls | | -| [`@docusaurus/string-literal-i18n-messages`](./string-literal-i18n-messages.md) | Enforce translate APIs to be called on plain text labels | ✅ | - -✅ = recommended - -## Example configuration - -Here's an example configuration: - -```js title=".eslintrc.js" -module.exports = { - extends: ['plugin:@docusaurus/recommended'], - plugins: ['@docusaurus'], - rules: { - '@docusaurus/no-untranslated-text': [ - 'warn', - {ignoredStrings: ['·', '—', '×']}, - ], - }, -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/misc/eslint-plugin/no-untranslated-text.md b/website/versioned_docs/version-2.0.0-rc.1/api/misc/eslint-plugin/no-untranslated-text.md deleted file mode 100644 index 3829a915bad9..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/misc/eslint-plugin/no-untranslated-text.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -slug: /api/misc/@docusaurus/eslint-plugin/no-untranslated-text ---- - -# no-untranslated-text - -import APITable from '@site/src/components/APITable'; - -Enforce text labels in JSX to be wrapped by translate calls. - -When the [i18n feature](../../../i18n/i18n-introduction.md) is used, this rule ensures that all labels appearing on the website are translatable, so no string accidentally slips through untranslated. - -## Rule Details {#details} - -Examples of **incorrect** code for this rule: - -```js -// Hello World is not translated -<Component>Hello World</Component> -``` - -Examples of **correct** code for this rule: - -```js -// Hello World is translated -<Component> - <Translate>Hello World</Translate> -</Component> -``` - -## Rule Configuration {#configuration} - -Accepted fields: - -```mdx-code-block -<APITable> -``` - -| Option | Type | Default | Description | -| --- | --- | --- | --- | -| `ignoredStrings` | `string[]` | `[]` | Text labels that only contain strings in this list will not be reported. | - -```mdx-code-block -</APITable> -``` - -## When Not To Use It {#when-not-to-use} - -If you're not using the [i18n feature](../../../i18n/i18n-introduction.md), you can disable this rule. You can also disable this rule where the text is not supposed to be translated. - -## Further Reading {#further-reading} - -- https://docusaurus.io/docs/docusaurus-core#translate -- https://docusaurus.io/docs/docusaurus-core#translate-imperative diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/misc/eslint-plugin/string-literal-i18n-messages.md b/website/versioned_docs/version-2.0.0-rc.1/api/misc/eslint-plugin/string-literal-i18n-messages.md deleted file mode 100644 index c216b78233a9..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/misc/eslint-plugin/string-literal-i18n-messages.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -slug: /api/misc/@docusaurus/eslint-plugin/string-literal-i18n-messages ---- - -# string-literal-i18n-messages - -Enforce translate APIs to be called on plain text labels. - -Docusaurus offers the [`docusaurus write-translations`](../../../cli.md#docusaurus-write-translations-sitedir) API, which statically extracts the text labels marked as translatable. Dynamic values used in `<Translate>` or `translate()` calls will fail to be extracted. This rule will ensure that all translate calls are statically extractable. - -## Rule Details {#details} - -Examples of **incorrect** code for this rule: - -```js -const text = 'Some text to be translated' - -// Invalid <Translate> child -<Translate>{text}</Translate> - -// Invalid message attribute -translate({message: text}) -``` - -Examples of **correct** code for this rule: - -```js -// Valid <Translate> child -<Translate>Some text to be translated</Translate> - -// Valid message attribute -translate({message: 'Some text to be translated'}) - -// Valid <Translate> child using values object as prop -<Translate values={{firstName: 'Sébastien'}}> - {'Welcome, {firstName}! How are you?'} -</Translate> - -// Valid message attribute using values object as second argument -translate({message: 'The logo of site {siteName}'}, {siteName: 'Docusaurus'}) -``` - -## When Not To Use It {#when-not-to-use} - -If you're not using the [i18n feature](../../../i18n/i18n-introduction.md), you can disable this rule. - -## Further Reading {#further-reading} - -- https://docusaurus.io/docs/docusaurus-core#translate -- https://docusaurus.io/docs/docusaurus-core#translate-imperative diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/misc/logger/demo.png b/website/versioned_docs/version-2.0.0-rc.1/api/misc/logger/demo.png deleted file mode 100644 index f3877552104f..000000000000 Binary files a/website/versioned_docs/version-2.0.0-rc.1/api/misc/logger/demo.png and /dev/null differ diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/misc/logger/logger.md b/website/versioned_docs/version-2.0.0-rc.1/api/misc/logger/logger.md deleted file mode 100644 index 51aa14163df4..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/misc/logger/logger.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -sidebar_position: 2 -slug: /api/misc/@docusaurus/logger ---- - -# 📦 logger - -An encapsulated logger for semantically formatting console messages. - -Authors of packages in the Docusaurus ecosystem are encouraged to use this package to provide unified log formats. - -## APIs - -It exports a single object as default export: `logger`. `logger` has the following properties: - -- Some useful colors. - - `red` - - `yellow` - - `green` - - `bold` - - `dim` -- Formatters. These functions all have the signature `(msg: unknown) => string`. Note that their implementations are not guaranteed. You should only care about their semantics. - - `path`: formats a file path. - - `url`: formats a URL. - - `name`: formats an identifier. - - `code`: formats a code snippet. - - `subdue`: subdues the text. - - `num`: formats a number. -- The `interpolate` function. It is a template literal tag. The syntax can be found below. -- Logging functions. All logging functions can both be used as normal functions (similar to the `console.log` family, but only accepts one parameter) or template literal tags. - - `info`: prints information. - - `warn`: prints a warning that should be payed attention to. - - `error`: prints an error (not necessarily halting the program) that signals significant problems. - - `success`: prints a success message. -- The `report` function. It takes a `ReportingSeverity` value (`ignore`, `log`, `warn`, `throw`) and reports a message according to the severity. - -:::caution A word on the `error` formatter - -Beware that an `error` message, even when it doesn't hang the program, is likely going to cause confusion. When users inspect logs and find an `[ERROR]`, even when the build succeeds, they will assume something is going wrong. Use it sparingly. - -Docusaurus only uses `logger.error` when printing messages immediately before throwing an error, or when user has set the reporting severity of `onBrokenLink`, etc. to `"error"`. - -In addition, `warn` and `error` will color the **entire** message for better attention. If you are printing large blocks of help text about an error, better use `logger.info`. - -::: - -### Using the template literal tag - -The template literal tag evaluates the template and expressions embedded. `interpolate` returns a new string, while other logging functions prints it. Below is a typical usage: - -```js -logger.info`Hello name=${name}! You have number=${money} dollars. Here are the ${ - items.length > 1 ? 'items' : 'item' -} on the shelf: ${items} -To buy anything, enter code=${'buy x'} where code=${'x'} is the item's name; to quit, press code=${'Ctrl + C'}.`; -``` - -An embedded expression is optionally preceded by a flag in the form `[a-z]+=` (a few lowercase letters, followed by an equals sign, directly preceding the embedded expression). If the expression is not preceded by any flag, it's printed out as-is. Otherwise, it's formatted with one of the formatters: - -- `path=`: `path` -- `url=`: `url` -- `name=`: `name` -- `code=`: `code` -- `subdue=`: `subdue` -- `number=`: `num` - -If the expression is an array, it's formatted by `` `\n- ${array.join('\n- ')}\n` `` (note it automatically gets a leading line end). Each member is formatted by itself and the bullet is not formatted. So you would see the above message printed as: - -![demo](./demo.png) diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/README.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/README.md deleted file mode 100644 index a59fc2059f47..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/README.md +++ /dev/null @@ -1,146 +0,0 @@ -# Plugin Method References - -:::caution - -This section is a work in progress. Anchor links or even URLs are not guaranteed to be stable. - -::: - -Plugin APIs are shared by themes and plugins—themes are loaded just like plugins. - -## Plugin module {#plugin-module} - -Every plugin is imported as a module. The module is expected to have the following members: - -- A **default export**: the constructor function for the plugin. -- **Named exports**: the [static methods](./static-methods.md) called before plugins are initialized. - -## Plugin constructor {#plugin-constructor} - -The plugin module's default export is a constructor function with the signature `(context: LoadContext, options: PluginOptions) => Plugin | Promise<Plugin>`. - -### `context` {#context} - -`context` is plugin-agnostic, and the same object will be passed into all plugins used for a Docusaurus website. The `context` object contains the following fields: - -```ts -type LoadContext = { - siteDir: string; - generatedFilesDir: string; - siteConfig: DocusaurusConfig; - outDir: string; - baseUrl: string; -}; -``` - -### `options` {#options} - -`options` are the [second optional parameter when the plugins are used](../../using-plugins.md#configuring-plugins). `options` are plugin-specific and are specified by users when they use them in `docusaurus.config.js`. If there's a [`validateOptions`](./static-methods.md#validateOptions) function exported, the `options` will be validated and normalized beforehand. - -Alternatively, if a preset contains the plugin, the preset will then be in charge of passing the correct options into the plugin. It is up to the individual plugin to define what options it takes. - -## Example {#example} - -Here's a mental model for a presumptuous plugin implementation. - -```js -// A JavaScript function that returns an object. -// `context` is provided by Docusaurus. Example: siteConfig can be accessed from context. -// `opts` is the user-defined options. -async function myPlugin(context, opts) { - return { - // A compulsory field used as the namespace for directories to cache - // the intermediate data for each plugin. - // If you're writing your own local plugin, you will want it to - // be unique in order not to potentially conflict with imported plugins. - // A good way will be to add your own project name within. - name: 'docusaurus-my-project-cool-plugin', - - async loadContent() { - // The loadContent hook is executed after siteConfig and env has been loaded. - // You can return a JavaScript object that will be passed to contentLoaded hook. - }, - - async contentLoaded({content, actions}) { - // The contentLoaded hook is done after loadContent hook is done. - // `actions` are set of functional API provided by Docusaurus (e.g. addRoute) - }, - - async postBuild(props) { - // After docusaurus <build> finish. - }, - - // TODO - async postStart(props) { - // docusaurus <start> finish - }, - - // TODO - afterDevServer(app, server) { - // https://webpack.js.org/configuration/dev-server/#devserverbefore - }, - - // TODO - beforeDevServer(app, server) { - // https://webpack.js.org/configuration/dev-server/#devserverafter - }, - - configureWebpack(config, isServer, utils, content) { - // Modify internal webpack config. If returned value is an Object, it - // will be merged into the final config using webpack-merge; - // If the returned value is a function, it will receive the config as the 1st argument and an isServer flag as the 2nd argument. - }, - - getPathsToWatch() { - // Paths to watch. - }, - - getThemePath() { - // Returns the path to the directory where the theme components can - // be found. - }, - - getClientModules() { - // Return an array of paths to the modules that are to be imported - // in the client bundle. These modules are imported globally before - // React even renders the initial UI. - }, - - extendCli(cli) { - // Register an extra command to enhance the CLI of Docusaurus - }, - - injectHtmlTags({content}) { - // Inject head and/or body HTML tags. - }, - - async getTranslationFiles({content}) { - // Return translation files - }, - - translateContent({content, translationFiles}) { - // translate the plugin content here - }, - - translateThemeConfig({themeConfig, translationFiles}) { - // translate the site themeConfig here - }, - - async getDefaultCodeTranslationMessages() { - // return default theme translations here - }, - }; -} - -myPlugin.validateOptions = ({options, validate}) => { - const validatedOptions = validate(myValidationSchema, options); - return validationOptions; -}; - -myPlugin.validateThemeConfig = ({themeConfig, validate}) => { - const validatedThemeConfig = validate(myValidationSchema, options); - return validatedThemeConfig; -}; - -module.exports = myPlugin; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/_category_.yml b/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/_category_.yml deleted file mode 100644 index 86cb36c24614..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/_category_.yml +++ /dev/null @@ -1,2 +0,0 @@ -label: Plugin method references -position: 1 diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/extend-infrastructure.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/extend-infrastructure.md deleted file mode 100644 index 1885129b7007..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/extend-infrastructure.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -sidebar_position: 2 ---- - -# Extending infrastructure - -Docusaurus has some infrastructure like hot reloading, CLI, and swizzling, that can be extended by external plugins. - -## `getPathsToWatch()` {#getPathsToWatch} - -Specifies the paths to watch for plugins and themes. The paths are watched by the dev server so that the plugin lifecycles are reloaded when contents in the watched paths change. Note that the plugins and themes modules are initially called with `context` and `options` from Node, which you may use to find the necessary directory information about the site. - -Use this for files that are consumed server-side, because theme files are automatically watched by Webpack dev server. - -Example: - -```js title="docusaurus-plugin/src/index.js" -const path = require('path'); -module.exports = function (context, options) { - return { - name: 'docusaurus-plugin', - // highlight-start - getPathsToWatch() { - const contentPath = path.resolve(context.siteDir, options.path); - return [`${contentPath}/**/*.{ts,tsx}`]; - }, - // highlight-end - }; -}; -``` - -## `extendCli(cli)` {#extendCli} - -Register an extra command to enhance the CLI of Docusaurus. `cli` is a [commander](https://www.npmjs.com/package/commander/v/5.1.0) object. - -:::caution - -The commander version matters! We use commander v5, and make sure you are referring to the right version documentation for available APIs. - -::: - -Example: - -```js title="docusaurus-plugin/src/index.js" -module.exports = function (context, options) { - return { - name: 'docusaurus-plugin', - // highlight-start - extendCli(cli) { - cli - .command('roll') - .description('Roll a random number between 1 and 1000') - .action(() => { - console.log(Math.floor(Math.random() * 1000 + 1)); - }); - }, - // highlight-end - }; -}; -``` - -## `getThemePath()` {#getThemePath} - -Returns the path to the directory where the theme components can be found. When your users call `swizzle`, `getThemePath` is called and its returned path is used to find your theme components. Relative paths are resolved against the folder containing the entry point. - -For example, your `getThemePath` can be: - -```js title="my-theme/src/index.js" -const path = require('path'); - -module.exports = function (context, options) { - return { - name: 'my-theme', - // highlight-start - getThemePath() { - return './theme'; - }, - // highlight-end - }; -}; -``` - -## `getTypeScriptThemePath()` {#getTypeScriptThemePath} - -Similar to `getThemePath()`, it should return the path to the directory where the source code of TypeScript theme components can be found. This path is purely for swizzling TypeScript theme components, and theme components under this path will **not** be resolved by Webpack. Therefore, it is not a replacement for `getThemePath()`. Typically, you can make the path returned by `getTypeScriptThemePath()` be your source directory, and make the path returned by `getThemePath()` be the compiled JavaScript output. - -:::tip - -For TypeScript theme authors: you are strongly advised to make your compiled output as human-readable as possible. Only strip type annotations and don't transpile any syntaxes, because they will be handled by Webpack's Babel loader based on the targeted browser versions. - -You should also format these files with Prettier. Remember—JS files can and will be directly consumed by your users. - -::: - -Example: - -```js title="my-theme/src/index.js" -const path = require('path'); - -module.exports = function (context, options) { - return { - name: 'my-theme', - // highlight-start - getThemePath() { - // Where compiled JavaScript output lives - return '../lib/theme'; - }, - getTypeScriptThemePath() { - // Where TypeScript source code lives - return '../src/theme'; - }, - // highlight-end - }; -}; -``` - -## `getSwizzleComponentList()` {#getSwizzleComponentList} - -**This is a static method, not attached to any plugin instance.** - -Returns a list of stable components that are considered safe for swizzling. These components will be swizzlable without `--danger`. All components are considered unstable by default. If an empty array is returned, all components are considered unstable. If `undefined` is returned, all components are considered stable. - -```js title="my-theme/src/index.js" -const swizzleAllowedComponents = [ - 'CodeBlock', - 'DocSidebar', - 'Footer', - 'NotFound', - 'SearchBar', - 'hooks/useTheme', - 'prism-include-languages', -]; - -myTheme.getSwizzleComponentList = () => swizzleAllowedComponents; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/i18n-lifecycles.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/i18n-lifecycles.md deleted file mode 100644 index 1002dd74a344..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/i18n-lifecycles.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -sidebar_position: 3 ---- - -# I18n lifecycles - -Plugins use these lifecycles to load i18n-related data. - -## `getTranslationFiles({content})` {#getTranslationFiles} - -Plugins declare the JSON translation files they want to use. - -Returns translation files `{path: string, content: ChromeI18nJSON}`: - -- `path`: relative to the plugin localized folder `i18n/[locale]/[pluginName]`. Extension `.json` should be omitted to remain generic. -- `content`: using the Chrome i18n JSON format. - -These files will be written by the [`write-translations` CLI](../../cli.md#docusaurus-write-translations-sitedir) to the plugin i18n subfolder, and will be read in the appropriate locale before calling [`translateContent()`](#translateContent) and [`translateThemeConfig()`](#translateThemeConfig) - -Example: - -```js -module.exports = function (context, options) { - return { - name: 'my-plugin', - // highlight-start - async getTranslationFiles({content}) { - return [ - { - path: 'sidebar-labels', - content: { - someSidebarLabel: { - message: 'Some Sidebar Label', - description: 'A label used in my plugin in the sidebar', - }, - someLabelFromContent: content.myLabel, - }, - }, - ]; - }, - // highlight-end - }; -}; -``` - -## `translateContent({content,translationFiles})` {#translateContent} - -Translate the plugin content, using the localized translation files. - -Returns the localized plugin content. - -The `contentLoaded()` lifecycle will be called with the localized plugin content returned by `translateContent()`. - -Example: - -```js -module.exports = function (context, options) { - return { - name: 'my-plugin', - // highlight-start - translateContent({content, translationFiles}) { - const myTranslationFile = translationFiles.find( - (f) => f.path === 'myTranslationFile', - ); - return { - ...content, - someContentLabel: myTranslationFile.someContentLabel.message, - }; - }, - // highlight-end - }; -}; -``` - -## `translateThemeConfig({themeConfig,translationFiles})` {#translateThemeConfig} - -Translate the site `themeConfig` labels, using the localized translation files. - -Returns the localized `themeConfig`. - -Example: - -```js -module.exports = function (context, options) { - return { - name: 'my-theme', - // highlight-start - translateThemeConfig({themeConfig, translationFiles}) { - const myTranslationFile = translationFiles.find( - (f) => f.path === 'myTranslationFile', - ); - return { - ...themeConfig, - someThemeConfigLabel: myTranslationFile.someThemeConfigLabel.message, - }; - }, - // highlight-end - }; -}; -``` - -## `async getDefaultCodeTranslationMessages()` {#getDefaultCodeTranslationMessages} - -Themes using the `<Translate>` API can provide default code translation messages. - -It should return messages in `Record<string, string>`, where keys are translation IDs and values are messages (without the description) localized using the site's current locale. - -Example: - -```js -module.exports = function (context, options) { - return { - name: 'my-theme', - // highlight-start - async getDefaultCodeTranslationMessages() { - return readJsonFile(`${context.i18n.currentLocale}.json`); - }, - // highlight-end - }; -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/lifecycle-apis.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/lifecycle-apis.md deleted file mode 100644 index 739b902d07de..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/lifecycle-apis.md +++ /dev/null @@ -1,420 +0,0 @@ ---- -sidebar_position: 1 -toc_max_heading_level: 4 ---- - -# Lifecycle APIs - -During the build, plugins are loaded in parallel to fetch their own contents and render them to routes. Plugins may also configure webpack or post-process the generated files. - -## `async loadContent()` {#loadContent} - -Plugins should use this lifecycle to fetch from data sources (filesystem, remote API, headless CMS, etc.) or do some server processing. The return value is the content it needs. - -For example, this plugin below return a random integer between 1 to 10 as content. - -```js title="docusaurus-plugin/src/index.js" -module.exports = function (context, options) { - return { - name: 'docusaurus-plugin', - // highlight-start - async loadContent() { - return 1 + Math.floor(Math.random() * 10); - }, - // highlight-end - }; -}; -``` - -## `async contentLoaded({content, actions})` {#contentLoaded} - -The data that was loaded in `loadContent` will be consumed in `contentLoaded`. It can be rendered to routes, registered as global data, etc. - -### `content` {#content} - -`contentLoaded` will be called _after_ `loadContent` is done. The return value of `loadContent()` will be passed to `contentLoaded` as `content`. - -### `actions` {#actions} - -`actions` contain three functions: - -#### `addRoute(config: RouteConfig): void` {#addRoute} - -Create a route to add to the website. - -```ts -type RouteConfig = { - path: string; - component: string; - modules?: RouteModules; - routes?: RouteConfig[]; - exact?: boolean; - priority?: number; -}; -type RouteModules = { - [module: string]: Module | RouteModules | RouteModules[]; -}; -type Module = - | { - path: string; - __import?: boolean; - query?: ParsedUrlQueryInput; - } - | string; -``` - -#### `createData(name: string, data: any): Promise<string>` {#createData} - -A declarative callback to create static data (generally JSON or string) which can later be provided to your routes as props. Takes the file name and data to be stored, and returns the actual data file's path. - -For example, this plugin below creates a `/friends` page which displays `Your friends are: Yangshun, Sebastien`: - -```jsx title="website/src/components/Friends.js" -import React from 'react'; - -export default function FriendsComponent({friends}) { - return <div>Your friends are {friends.join(',')}</div>; -} -``` - -```js title="docusaurus-friends-plugin/src/index.js" -export default function friendsPlugin(context, options) { - return { - name: 'docusaurus-friends-plugin', - // highlight-start - async contentLoaded({content, actions}) { - const {createData, addRoute} = actions; - // Create friends.json - const friends = ['Yangshun', 'Sebastien']; - const friendsJsonPath = await createData( - 'friends.json', - JSON.stringify(friends), - ); - - // Add the '/friends' routes, and ensure it receives the friends props - addRoute({ - path: '/friends', - component: '@site/src/components/Friends.js', - modules: { - // propName -> JSON file path - friends: friendsJsonPath, - }, - exact: true, - }); - }, - // highlight-end - }; -} -``` - -#### `setGlobalData(data: any): void` {#setGlobalData} - -This function permits one to create some global plugin data that can be read from any page, including the pages created by other plugins, and your theme layout. - -This data becomes accessible to your client-side/theme code through the [`useGlobalData`](../../docusaurus-core.md#useGlobalData) and [`usePluginData`](../../docusaurus-core.md#usePluginData) hooks. - -:::caution - -Global data is... global: its size affects the loading time of all pages of your site, so try to keep it small. Prefer `createData` and page-specific data whenever possible. - -::: - -For example, this plugin below creates a `/friends` page which displays `Your friends are: Yangshun, Sebastien`: - -```jsx title="website/src/components/Friends.js" -import React from 'react'; -import {usePluginData} from '@docusaurus/useGlobalData'; - -export default function FriendsComponent() { - const {friends} = usePluginData('my-friends-plugin'); - return <div>Your friends are {friends.join(',')}</div>; -} -``` - -```js title="docusaurus-friends-plugin/src/index.js" -export default function friendsPlugin(context, options) { - return { - name: 'docusaurus-friends-plugin', - // highlight-start - async contentLoaded({content, actions}) { - const {setGlobalData, addRoute} = actions; - // Create friends global data - setGlobalData({friends: ['Yangshun', 'Sebastien']}); - - // Add the '/friends' routes - addRoute({ - path: '/friends', - component: '@site/src/components/Friends.js', - exact: true, - }); - }, - // highlight-end - }; -} -``` - -## `configureWebpack(config, isServer, utils, content)` {#configureWebpack} - -Modifies the internal webpack config. If the return value is a JavaScript object, it will be merged into the final config using [`webpack-merge`](https://github.com/survivejs/webpack-merge). If it is a function, it will be called and receive `config` as the first argument and an `isServer` flag as the second argument. - -:::caution - -The API of `configureWebpack` will be modified in the future to accept an object (`configureWebpack({config, isServer, utils, content})`) - -::: - -### `config` {#config} - -`configureWebpack` is called with `config` generated according to client/server build. You may treat this as the base config to be merged with. - -### `isServer` {#isServer} - -`configureWebpack` will be called both in server build and in client build. The server build receives `true` and the client build receives `false` as `isServer`. - -### `utils` {#utils} - -`configureWebpack` also receives an util object: - -- `getStyleLoaders(isServer: boolean, cssOptions: {[key: string]: any}): Loader[]` -- `getJSLoader(isServer: boolean, cacheOptions?: {}): Loader | null` - -You may use them to return your webpack configuration conditionally. - -For example, this plugin below modify the webpack config to transpile `.foo` files. - -```js title="docusaurus-plugin/src/index.js" -module.exports = function (context, options) { - return { - name: 'custom-docusaurus-plugin', - // highlight-start - configureWebpack(config, isServer, utils) { - const {getJSLoader} = utils; - return { - module: { - rules: [ - { - test: /\.foo$/, - use: [getJSLoader(isServer), 'my-custom-webpack-loader'], - }, - ], - }, - }; - }, - // highlight-end - }; -}; -``` - -### `content` {#content-1} - -`configureWebpack` will be called both with the content loaded by the plugin. - -### Merge strategy {#merge-strategy} - -We merge the Webpack configuration parts of plugins into the global Webpack config using [webpack-merge](https://github.com/survivejs/webpack-merge). - -It is possible to specify the merge strategy. For example, if you want a webpack rule to be prepended instead of appended: - -```js title="docusaurus-plugin/src/index.js" -module.exports = function (context, options) { - return { - name: 'custom-docusaurus-plugin', - configureWebpack(config, isServer, utils) { - return { - // highlight-start - mergeStrategy: {'module.rules': 'prepend'}, - module: {rules: [myRuleToPrepend]}, - // highlight-end - }; - }, - }; -}; -``` - -Read the [webpack-merge strategy doc](https://github.com/survivejs/webpack-merge#merging-with-strategies) for more details. - -### Configuring dev server {#configuring-dev-server} - -The dev server can be configured through returning a `devServer` field. - -```js title="docusaurus-plugin/src/index.js" -module.exports = function (context, options) { - return { - name: 'custom-docusaurus-plugin', - configureWebpack(config, isServer, utils) { - return { - // highlight-start - devServer: { - open: '/docs', // Opens localhost:3000/docs instead of localhost:3000/ - }, - // highlight-end - }; - }, - }; -}; -``` - -## `configurePostCss(options)` {#configurePostCss} - -Modifies [`postcssOptions` of `postcss-loader`](https://webpack.js.org/loaders/postcss-loader/#postcssoptions) during the generation of the client bundle. - -Should return the mutated `postcssOptions`. - -By default, `postcssOptions` looks like this: - -```js -const postcssOptions = { - ident: 'postcss', - plugins: [require('autoprefixer')], -}; -``` - -Example: - -```js title="docusaurus-plugin/src/index.js" -module.exports = function (context, options) { - return { - name: 'docusaurus-plugin', - // highlight-start - configurePostCss(postcssOptions) { - // Appends new PostCSS plugin. - postcssOptions.plugins.push(require('postcss-import')); - return postcssOptions; - }, - // highlight-end - }; -}; -``` - -## `postBuild(props)` {#postBuild} - -Called when a (production) build finishes. - -```ts -interface Props { - siteDir: string; - generatedFilesDir: string; - siteConfig: DocusaurusConfig; - outDir: string; - baseUrl: string; - headTags: string; - preBodyTags: string; - postBodyTags: string; - routesPaths: string[]; - plugins: Plugin<any>[]; - content: Content; -} -``` - -Example: - -```js title="docusaurus-plugin/src/index.js" -module.exports = function (context, options) { - return { - name: 'docusaurus-plugin', - // highlight-start - async postBuild({siteConfig = {}, routesPaths = [], outDir}) { - // Print out to console all the rendered routes. - routesPaths.map((route) => { - console.log(route); - }); - }, - // highlight-end - }; -}; -``` - -## `injectHtmlTags({content})` {#injectHtmlTags} - -Inject head and/or body HTML tags to Docusaurus generated HTML. - -`injectHtmlTags` will be called both with the content loaded by the plugin. - -```ts -function injectHtmlTags(): { - headTags?: HtmlTags; - preBodyTags?: HtmlTags; - postBodyTags?: HtmlTags; -}; - -type HtmlTags = string | HtmlTagObject | (string | HtmlTagObject)[]; - -type HtmlTagObject = { - /** - * Attributes of the HTML tag - * E.g. `{'disabled': true, 'value': 'demo', 'rel': 'preconnect'}` - */ - attributes?: { - [attributeName: string]: string | boolean; - }; - /** - * The tag name e.g. `div`, `script`, `link`, `meta` - */ - tagName: string; - /** - * The inner HTML - */ - innerHTML?: string; -}; -``` - -Example: - -```js title="docusaurus-plugin/src/index.js" -module.exports = function (context, options) { - return { - name: 'docusaurus-plugin', - loadContent: async () => { - return {remoteHeadTags: await fetchHeadTagsFromAPI()}; - }, - // highlight-start - injectHtmlTags({content}) { - return { - headTags: [ - { - tagName: 'link', - attributes: { - rel: 'preconnect', - href: 'https://www.github.com', - }, - }, - ...content.remoteHeadTags, - ], - preBodyTags: [ - { - tagName: 'script', - attributes: { - charset: 'utf-8', - src: '/noflash.js', - }, - }, - ], - postBodyTags: [`<div> This is post body </div>`], - }; - }, - // highlight-end - }; -}; -``` - -## `getClientModules()` {#getClientModules} - -Returns an array of paths to the [client modules](../../advanced/client.md#client-modules) that are to be imported into the client bundle. - -As an example, to make your theme load a `customCss` or `customJs` file path from `options` passed in by the user: - -```js title="my-theme/src/index.js" -const path = require('path'); - -module.exports = function (context, options) { - const {customCss, customJs} = options || {}; - return { - name: 'name-of-my-theme', - // highlight-start - getClientModules() { - return [customCss, customJs]; - }, - // highlight-end - }; -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/static-methods.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/static-methods.md deleted file mode 100644 index e9caa3ba3865..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugin-methods/static-methods.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -sidebar_position: 4 ---- - -# Static methods - -Static methods are not part of the plugin instance—they are attached to the constructor function. These methods are used to validate and normalize the plugin options and theme config, which are then used as constructor parameters to initialize the plugin instance. - -## `validateOptions({options, validate})` {#validateOptions} - -Returns validated and normalized options for the plugin. This method is called before the plugin is initialized. You must return the options since they will be passed to the plugin during initialization. - -### `options` {#options} - -`validateOptions` is called with `options` passed to plugin for validation and normalization. - -### `validate` {#validate} - -`validateOptions` is called with `validate` function which takes a **[Joi](https://www.npmjs.com/package/joi)** schema and options as the arguments, returns validated and normalized options. `validate` will automatically handle error and validation config. - -:::tip - -[Joi](https://www.npmjs.com/package/joi) is recommended for validation and normalization of options. - -To avoid mixing Joi versions, use `const {Joi} = require("@docusaurus/utils-validation")` - -::: - -If you don't use **[Joi](https://www.npmjs.com/package/joi)** for validation you can throw an Error in case of invalid options and return options in case of success. - -```js title="my-plugin/src/index.js" -function myPlugin(context, options) { - return { - name: 'docusaurus-plugin', - // rest of methods - }; -} - -// highlight-start -myPlugin.validateOptions = ({options, validate}) => { - const validatedOptions = validate(myValidationSchema, options); - return validationOptions; -}; -// highlight-end - -module.exports = myPlugin; -``` - -In TypeScript, you can also choose to export this as a separate named export. - -```ts title="my-plugin/src/index.ts" -export default function (context, options) { - return { - name: 'docusaurus-plugin', - // rest of methods - }; -} - -// highlight-start -export function validateOptions({options, validate}) { - const validatedOptions = validate(myValidationSchema, options); - return validationOptions; -} -// highlight-end -``` - -## `validateThemeConfig({themeConfig, validate})` {#validateThemeConfig} - -Return validated and normalized configuration for the theme. - -### `themeConfig` {#themeConfig} - -`validateThemeConfig` is called with `themeConfig` provided in `docusaurus.config.js` for validation and normalization. - -### `validate` {#validate-1} - -`validateThemeConfig` is called with `validate` function which takes a **[Joi](https://www.npmjs.com/package/joi)** schema and `themeConfig` as the arguments, returns validated and normalized options. `validate` will automatically handle error and validation config. - -:::tip - -[Joi](https://www.npmjs.com/package/joi) is recommended for validation and normalization of theme config. - -To avoid mixing Joi versions, use `const {Joi} = require("@docusaurus/utils-validation")` - -::: - -If you don't use **[Joi](https://www.npmjs.com/package/joi)** for validation you can throw an Error in case of invalid options. - -```js title="my-theme/src/index.js" -function myPlugin(context, options) { - return { - name: 'docusaurus-plugin', - // rest of methods - }; -} - -// highlight-start -myPlugin.validateThemeConfig = ({themeConfig, validate}) => { - const validatedThemeConfig = validate(myValidationSchema, options); - return validatedThemeConfig; -}; -// highlight-end - -module.exports = validateThemeConfig; -``` - -In TypeScript, you can also choose to export this as a separate named export. - -```ts title="my-theme/src/index.ts" -export default function (context, options) { - return { - name: 'docusaurus-plugin', - // rest of methods - }; -} - -// highlight-start -export function validateThemeConfig({themeConfig, validate}) { - const validatedThemeConfig = validate(myValidationSchema, options); - return validatedThemeConfig; -} -// highlight-end -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/_category_.yml b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/_category_.yml deleted file mode 100644 index cffabddbd5db..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/_category_.yml +++ /dev/null @@ -1,5 +0,0 @@ -label: Plugins -position: 2 -link: - type: doc - id: api/plugins/plugins-overview # Dogfood using a "qualified id" diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/overview.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/overview.md deleted file mode 100644 index f1d1656aa38c..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/overview.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -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.md) -- [@docusaurus/plugin-content-blog](./plugin-content-blog.md) -- [@docusaurus/plugin-content-pages](./plugin-content-pages.md) - -## Behavior plugins {#behavior-plugins} - -These plugins will add a useful behavior to your Docusaurus site. - -- [@docusaurus/plugin-debug](./plugin-debug.md) -- [@docusaurus/plugin-sitemap](./plugin-sitemap.md) -- [@docusaurus/plugin-pwa](./plugin-pwa.md) -- [@docusaurus/plugin-client-redirects](./plugin-client-redirects.md) -- [@docusaurus/plugin-ideal-image](./plugin-ideal-image.md) -- [@docusaurus/plugin-google-analytics](./plugin-google-analytics.md) -- [@docusaurus/plugin-google-gtag](./plugin-google-gtag.md) diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-client-redirects.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-client-redirects.md deleted file mode 100644 index a24ac3e24b84..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-client-redirects.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -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. - -:::caution production only - -This plugin is always inactive in development and **only active in production** because it works on the build output. - -::: - -:::caution - -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><a href="#RedirectRule">RedirectRule</a>[]</code> | `[]` | The list of redirect rules. | -| `createRedirects` | <code><a href="#CreateRedirectsFn">CreateRedirectsFn</a></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.md#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" -module.exports = { - 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 - ], - ], -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-content-blog.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-content-blog.md deleted file mode 100644 index 696b4102858d..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-content-blog.md +++ /dev/null @@ -1,270 +0,0 @@ ---- -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. - -:::caution 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](#ex-config-preset). - -::: - -## 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 \| <a href="#EditUrlFn">EditUrlFn</a></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`. **DO NOT** include a trailing slash. | -| `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*-->/` | 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><a href="#FeedType">FeedType</a> \| <a href="#FeedType">FeedType</a>[] \| 'all' \| null</code> | **Required** | Type of feed to be generated. Use `null` to disable generation. | -| `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. | - -```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'; -``` - -### 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('remark-math')], - rehypePlugins: [], - beforeDefaultRemarkPlugins: [], - beforeDefaultRehypePlugins: [], - truncateMarker: /<!--\s*(truncate)\s*-->/, - showReadingTime: true, - feedOptions: { - type: '', - title: '', - description: '', - copyright: '', - language: undefined, - }, -}; -``` - -## Markdown front matter {#markdown-front-matter} - -Markdown documents can use the following Markdown 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` | A boolean flag to indicate that the blog post is work-in-progress. Draft blog posts will only be displayed during development. | -| `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 when displaying the link to your post. | -| `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: `/`. | - -```mdx-code-block -</APITable> -``` - -```ts -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 v2 -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 2. -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.md) 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.md#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 -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-content-docs.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-content-docs.md deleted file mode 100644 index d645f726738f..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-content-docs.md +++ /dev/null @@ -1,362 +0,0 @@ ---- -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.md) 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. - -::: - -## 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 \| <a href="#EditUrlFunction">EditUrlFunction</a></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#collapsible-categories) | -| `sidebarCollapsed` | `boolean` | `true` | Whether sidebar categories are collapsed by default. See also [Expanded categories by default](/docs/sidebar#expanded-categories-by-default) | -| `sidebarItemsGenerator` | <a href="#SidebarGenerator"><code>SidebarGenerator</code></a> | _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#customize-the-sidebar-items-generator) | -| `numberPrefixParser` | <code>boolean \|</code> <a href="#PrefixParser"><code>PrefixParser</code></a> | _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#using-number-prefixes) | -| `docLayoutComponent` | `string` | `'@theme/DocPage'` | Root layout component of each doc page. Provides the version data context, and is not unmounted when switching docs. | -| `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. | -| `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` | <a href="#VersionsConfig"><code>VersionsConfig</code></a> | `{}` | 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 VersionsConfig = { - [versionName: string]: { - /** - * 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; - /** Add a custom class name to the <html> element of each doc */ - className?: string; - }; -}; -``` - -### 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}; - }, - docLayoutComponent: '@theme/DocPage', - docItemComponent: '@theme/DocItem', - remarkPlugins: [require('remark-math')], - 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 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-sidebar-metadata). | -| `sidebar_class_name` | `string` | `undefined` | Gives the corresponding sidebar label a special class name when using autogenerated sidebars. | -| `sidebar_custom_props` | `string` | `undefined` | Assign custom metadata to the sidebar item referencing this doc. | -| `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#using-number-prefixes). | -| `custom_edit_url` | `string` | Computed using the `editUrl` plugin option | The URL for editing this document. | -| `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 when displaying the link to your post. | -| `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` | A boolean flag to indicate that a document is a work-in-progress. Draft documents will only be displayed during development. | -| `last_update` | `FileChange` | `undefined` | Allows overriding the last updated author and/or 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 Tag = string | {label: string; permalink: string}; -``` - -```ts -type FileChange = {date: string; author: 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.md) 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.md#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 -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-content-pages.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-content-pages.md deleted file mode 100644 index b6334f5af7ca..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-content-pages.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -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.md) 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. - -::: - -## 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('remark-math')], - rehypePlugins: [], - beforeDefaultRemarkPlugins: [], - beforeDefaultRehypePlugins: [], -}; -``` - -## i18n {#i18n} - -Read the [i18n introduction](../../i18n/i18n-introduction.md) 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.md#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 -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-debug.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-debug.md deleted file mode 100644 index bca9ac69192e..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-debug.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -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" -module.exports = { - 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. - -::: - -## 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.md#docusauruspreset-classic): - -```js title="docusaurus.config.js" -module.exports = { - 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" -module.exports = { - // highlight-next-line - plugins: ['@docusaurus/plugin-debug'], -}; -``` - -```mdx-code-block -</TabItem> -</Tabs> -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-google-analytics.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-google-analytics.md deleted file mode 100644 index 1426e6265a1c..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-google-analytics.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -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.md) instead. - -:::caution 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. - -::: - -## 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, -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-google-gtag.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-google-gtag.md deleted file mode 100644 index db414c4d0f21..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-google-gtag.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -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! - -::: - -:::caution 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. - -::: - -## Configuration {#configuration} - -Accepted fields: - -```mdx-code-block -<APITable> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `trackingID` | `string` | **Required** | The tracking ID of your gtag 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: gtag -// Plugin Options: @docusaurus/plugin-google-gtag - -const config = { - trackingID: 'G-226F0LR9KE', - anonymizeIP: true, -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-ideal-image.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-ideal-image.md deleted file mode 100644 index e682c3943a75..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-ideal-image.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -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')} /> -``` - -## 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" -module.exports = { - 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 - ], - ], -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-pwa.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-pwa.md deleted file mode 100644 index 71f63febc643..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-pwa.md +++ /dev/null @@ -1,303 +0,0 @@ ---- -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" -module.exports = { - 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. - -![pwa_install.gif](/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. - -> ### [What is Precaching?](https://developers.google.com/web/tools/workbox/modules/workbox-precaching) -> -> 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. - -:::caution - -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 - -:::caution - -Use this carefully: some users may not like to be forced to use the offline mode. - -::: - -:::danger - -It is not possible to detect if an as a PWA in a very reliable way. - -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://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.injectManifest) 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" -module.exports = { - 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 -module.exports = { - 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.md) 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). - -![pwa_reload.gif](/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. diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-sitemap.md b/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-sitemap.md deleted file mode 100644 index 5bfdc50f2b18..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/plugins/plugin-sitemap.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -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. - -:::caution 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](#ex-config-preset). - -::: - -## Configuration {#configuration} - -Accepted fields: - -```mdx-code-block -<APITable> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `changefreq` | `string` | `'weekly'` | See [sitemap docs](https://www.sitemaps.org/protocol.html#xmlTagDefinitions) | -| `priority` | `number` | `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.md#noIndex): results in no sitemap generated -- [`trailingSlash`](../docusaurus.config.js.md#trailingSlash): determines if the URLs in the sitemap have trailing slashes - -::: - -### 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 = { - changefreq: 'weekly', - priority: 0.5, - ignorePatterns: ['/tags/**'], - filename: 'sitemap.xml', -}; -``` - -You can find your sitemap at `/sitemap.xml`. diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/themes/_category_.yml b/website/versioned_docs/version-2.0.0-rc.1/api/themes/_category_.yml deleted file mode 100644 index a0ceda5d5956..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/themes/_category_.yml +++ /dev/null @@ -1,5 +0,0 @@ -label: Themes -position: 3 -link: - type: doc - id: themes-overview # Dogfood using a "local id" diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/themes/overview.md b/website/versioned_docs/version-2.0.0-rc.1/api/themes/overview.md deleted file mode 100644 index f16eff35b511..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/themes/overview.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_position: 0 -id: themes-overview -sidebar_label: Themes overview -slug: /api/themes ---- - -# Docusaurus themes - -We provide official Docusaurus themes. - -## Main themes {#main-themes} - -The main themes implement the user interface for the [docs](../plugins/plugin-content-docs.md), [blog](../plugins/plugin-content-blog.md) and [pages](../plugins/plugin-content-pages.md) plugins. - -- [@docusaurus/theme-classic](./theme-classic.md) -- 🚧 other themes are planned - -:::caution - -The goal is to have all themes share the exact same features, user-experience and configuration. - -Only the UI design and underlying styling framework should change, and you should be able to change theme easily. - -We are not there yet: only the classic theme is production ready. - -::: - -## Enhancement themes {#enhancement-themes} - -These themes will enhance the existing main themes with additional user-interface related features. - -- [@docusaurus/theme-live-codeblock](./theme-live-codeblock.md) -- [@docusaurus/theme-search-algolia](./theme-search-algolia.md) diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-classic.md b/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-classic.md deleted file mode 100644 index cba54b875aeb..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-classic.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -sidebar_position: 2 -slug: /api/themes/@docusaurus/theme-classic ---- - -# 📦 theme-classic - -The classic theme for Docusaurus. - -You can refer to the [theme configuration page](theme-configuration.md) for more details on the configuration. - -```bash npm2yarn -npm install --save @docusaurus/theme-classic -``` - -:::tip - -If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. - -::: - -## Configuration {#configuration} - -Accepted fields: - -```mdx-code-block -<APITable> -``` - -| Option | Type | Default | Description | -| --- | --- | --- | --- | -| `customCss` | <code>string[] \| string</code> | `[]` | Stylesheets to be imported globally as [client modules](../../advanced/client.md#client-modules). Relative paths are resolved against the site directory. | - -```mdx-code-block -</APITable> -``` - -:::note - -Most configuration for the theme is done in `themeConfig`, which can be found in [theme configuration](./theme-configuration.md). - -::: - -### Example configuration {#ex-config} - -You can configure this theme through preset options or plugin options. - -:::tip - -Most Docusaurus users configure this plugin through the preset options. - -::: - -```js config-tabs -// Preset Options: theme -// Plugin Options: @docusaurus/theme-classic - -const config = { - customCss: require.resolve('./src/css/custom.css'), -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-configuration.md b/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-configuration.md deleted file mode 100644 index 5ad039269351..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-configuration.md +++ /dev/null @@ -1,1086 +0,0 @@ ---- -sidebar_position: 1 -sidebar_label: Configuration -slug: /api/themes/configuration -toc_max_heading_level: 4 ---- - -# Theme configuration - -import APITable from '@site/src/components/APITable'; - -This configuration applies to all [main themes](./overview.md). - -## Common {#common} - -### Color mode {#color-mode---dark-mode} - -The classic theme provides by default light and dark mode support, with a navbar switch for the user. - -It is possible to customize the color mode support within the `colorMode` object. - -Accepted fields: - -```mdx-code-block -<APITable> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `defaultMode` | <code>'light' \| 'dark'</code> | `'light'` | The color mode when user first visits the site. | -| `disableSwitch` | `boolean` | `false` | Hides the switch in the navbar. Useful if you want to support a single color mode. | -| `respectPrefersColorScheme` | `boolean` | `false` | Whether to use the `prefers-color-scheme` media-query, using user system preferences, instead of the hardcoded `defaultMode`. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - // highlight-start - colorMode: { - defaultMode: 'light', - disableSwitch: false, - respectPrefersColorScheme: false, - }, - // highlight-end - }, -}; -``` - -:::caution - -With `respectPrefersColorScheme: true`, the `defaultMode` is overridden by user system preferences. - -If you only want to support one color mode, you likely want to ignore user system preferences. - -::: - -### Meta image {#meta-image} - -You can configure a default image that will be used for your meta tag, in particular `og:image` and `twitter:image`. - -Accepted fields: - -```mdx-code-block -<APITable> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `image` | `string` | `undefined` | The meta image URL for the site. Relative to your site's "static" directory. Cannot be SVGs. Can be external URLs too. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - // highlight-next-line - image: 'img/docusaurus.png', - }, -}; -``` - -### Metadata {#metadata} - -You can configure additional HTML metadata (and override existing ones). - -Accepted fields: - -```mdx-code-block -<APITable> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `metadata` | `Metadata[]` | `[]` | Any field will be directly passed to the `<meta />` tag. Possible fields include `id`, `name`, `property`, `content`, `itemprop`, etc. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - // highlight-next-line - metadata: [{name: 'twitter:card', content: 'summary'}], - }, -}; -``` - -### Announcement bar {#announcement-bar} - -Sometimes you want to announce something in your website. Just for such a case, you can add an announcement bar. This is a non-fixed and optionally dismissible panel above the navbar. All configuration are in the `announcementBar` object. - -Accepted fields: - -```mdx-code-block -<APITable name="announcement-bar"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `id` | `string` | `'announcement-bar'` | Any value that will identify this message. | -| `content` | `string` | `''` | The text content of the announcement. HTML will be interpolated. | -| `backgroundColor` | `string` | `'#fff'` | Background color of the entire bar. | -| `textColor` | `string` | `'#000'` | Announcement text color. | -| `isCloseable` | `boolean` | `true` | Whether this announcement can be dismissed with a '×' button. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - // highlight-start - announcementBar: { - id: 'support_us', - content: - 'We are looking to revamp our docs, please fill <a target="_blank" rel="noopener noreferrer" href="#">this survey</a>', - backgroundColor: '#fafbfc', - textColor: '#091E42', - isCloseable: false, - }, - // highlight-end - }, -}; -``` - -## Navbar {#navbar} - -Accepted fields: - -```mdx-code-block -<APITable name="navbar-overview"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `title` | `string` | `undefined` | Title for the navbar. | -| `logo` | _See below_ | `undefined` | Customization of the logo object. | -| `items` | `NavbarItem[]` | `[]` | A list of navbar items. See specification below. | -| `hideOnScroll` | `boolean` | `false` | Whether the navbar is hidden when the user scrolls down. | -| `style` | <code>'primary' \| 'dark'</code> | Same as theme | Sets the navbar style, ignoring the dark/light theme. | - -```mdx-code-block -</APITable> -``` - -### Navbar logo {#navbar-logo} - -The logo can be placed in [static folder](static-assets.md). Logo URL is set to base URL of your site by default. Although you can specify your own URL for the logo, if it is an external link, it will open in a new tab. In addition, you can override a value for the target attribute of logo link, it can come in handy if you are hosting docs website in a subdirectory of your main website, and in which case you probably do not need a link in the logo to the main website will open in a new tab. - -To improve dark mode support, you can also set a different logo for this mode. - -Accepted fields: - -```mdx-code-block -<APITable name="navbar-logo"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `alt` | `string` | `undefined` | Alt tag for the logo image. | -| `src` | `string` | **Required** | URL to the logo image. Base URL is appended by default. | -| `srcDark` | `string` | `logo.src` | An alternative image URL to use in dark mode. | -| `href` | `string` | `siteConfig.baseUrl` | Link to navigate to when the logo is clicked. | -| `width` | <code>string \| number</code> | `undefined` | Specifies the `width` attribute. | -| `height` | <code>string \| number</code> | `undefined` | Specifies the `height` attribute. | -| `target` | `string` | Calculated based on `href` (external links will open in a new tab, all others in the current one). | The `target` attribute of the link; controls whether the link is opened in a new tab, the current one, or otherwise. | -| `className` | `string` | `undefined` | CSS class applied to the image. | -| `style` | `object` | `undefined` | CSS inline style object. React/JSX flavor, using camelCase properties. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - title: 'Site Title', - // highlight-start - logo: { - alt: 'Site Logo', - src: 'img/logo.svg', - srcDark: 'img/logo_dark.svg', - href: 'https://docusaurus.io/', - target: '_self', - width: 32, - height: 32, - className: 'custom-navbar-logo-class', - style: {border: 'solid red'}, - }, - // highlight-end - }, - }, -}; -``` - -### Navbar items {#navbar-items} - -You can add items to the navbar via `themeConfig.navbar.items`. - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - // highlight-start - items: [ - { - type: 'doc', - position: 'left', - docId: 'introduction', - label: 'Docs', - }, - {to: 'blog', label: 'Blog', position: 'left'}, - { - type: 'docsVersionDropdown', - position: 'right', - }, - { - type: 'localeDropdown', - position: 'right', - }, - { - href: 'https://github.com/facebook/docusaurus', - position: 'right', - className: 'header-github-link', - 'aria-label': 'GitHub repository', - }, - ], - // highlight-end - }, - }, -}; -``` - -The items can have different behaviors based on the `type` field. The sections below will introduce you to all the types of navbar items available. - -#### Navbar link {#navbar-link} - -By default, Navbar items are regular links (internal or external). - -React Router should automatically apply active link styling to links, but you can use `activeBasePath` in edge cases. For cases in which a link should be active on several different paths (such as when you have multiple doc folders under the same sidebar), you can use `activeBaseRegex`. `activeBaseRegex` is a more flexible alternative to `activeBasePath` and takes precedence over it -- Docusaurus parses it into a regular expression that is tested against the current URL. - -Outbound (external) links automatically get `target="_blank" rel="noopener noreferrer"` attributes. - -Accepted fields: - -```mdx-code-block -<APITable name="navbar-link"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `type` | `'default'` | Optional | Sets the type of this item to a link. | -| `label` | `string` | **Required** | The name to be shown for this item. | -| `html` | `string` | Optional | Same as `label`, but renders pure HTML instead of text content. | -| `to` | `string` | **Required** | Client-side routing, used for navigating within the website. The baseUrl will be automatically prepended to this value. | -| `href` | `string` | **Required** | A full-page navigation, used for navigating outside of the website. **Only one of `to` or `href` should be used.** | -| `prependBaseUrlToHref` | `boolean` | `false` | Prepends the baseUrl to `href` values. | -| `position` | <code>'left' \| 'right'</code> | `'left'` | The side of the navbar this item should appear on. | -| `activeBasePath` | `string` | `to` / `href` | To apply the active class styling on all routes starting with this path. This usually isn't necessary. | -| `activeBaseRegex` | `string` | `undefined` | Alternative to `activeBasePath` if required. | -| `className` | `string` | `''` | Custom CSS class (for styling any item). | - -```mdx-code-block -</APITable> -``` - -:::note - -In addition to the fields above, you can specify other arbitrary attributes that can be applied to a HTML link. - -::: - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - // highlight-start - { - to: 'docs/introduction', - // Only one of "to" or "href" should be used - // href: 'https://www.facebook.com', - label: 'Introduction', - // Only one of "label" or "html" should be used - // html: '<b>Introduction</b>' - position: 'left', - activeBaseRegex: 'docs/(next|v8)', - target: '_blank', - }, - // highlight-end - ], - }, - }, -}; -``` - -#### Navbar dropdown {#navbar-dropdown} - -Navbar items of the type `dropdown` has the additional `items` field, an inner array of navbar items. - -Navbar dropdown items only accept the following **"link-like" item types**: - -- [Navbar link](#navbar-link) -- [Navbar doc link](#navbar-doc-link) -- [Navbar docs version](#navbar-docs-version) -- [Navbar doc sidebar](#navbar-doc-sidebar) -- [Navbar with custom HTML](#navbar-with-custom-html) - -Note that the dropdown base item is a clickable link as well, so this item can receive any of the props of a [plain navbar link](#navbar-link). - -Accepted fields: - -```mdx-code-block -<APITable name="navbar-dropdown"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `type` | `'dropdown'` | Optional | Sets the type of this item to a dropdown. | -| `label` | `string` | **Required** | The name to be shown for this item. | -| `items` | <code>[LinkLikeItem](#navbar-dropdown)[]</code> | **Required** | The items to be contained in the dropdown. | -| `position` | <code>'left' \| 'right'</code> | `'left'` | The side of the navbar this item should appear on. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - // highlight-start - { - type: 'dropdown', - label: 'Community', - position: 'left', - items: [ - { - label: 'Facebook', - href: 'https://www.facebook.com', - }, - { - type: 'doc', - label: 'Social', - docId: 'social', - }, - // ... more items - ], - }, - // highlight-end - ], - }, - }, -}; -``` - -#### Navbar doc link {#navbar-doc-link} - -If you want to link to a specific doc, this special navbar item type will render the link to the doc of the provided `docId`. It will get the class `navbar__link--active` as long as you browse a doc of the same sidebar. - -Accepted fields: - -```mdx-code-block -<APITable name="navbar-doc-link"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `type` | `'doc'` | **Required** | Sets the type of this item to a doc link. | -| `docId` | `string` | **Required** | The ID of the doc that this item links to. | -| `label` | `string` | `docId` | The name to be shown for this item. | -| `position` | <code>'left' \| 'right'</code> | `'left'` | The side of the navbar this item should appear on. | -| `docsPluginId` | `string` | `'default'` | The ID of the docs plugin that the doc belongs to. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - // highlight-start - { - type: 'doc', - position: 'left', - docId: 'introduction', - label: 'Docs', - }, - // highlight-end - ], - }, - }, -}; -``` - -#### Navbar linked to a sidebar {#navbar-doc-sidebar} - -You can link a navbar item to the first document link (which can be a doc link or a generated category index) of a given sidebar without having to hardcode a doc ID. - -Accepted fields: - -```mdx-code-block -<APITable name="navbar-doc-sidebar"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `type` | `'docSidebar'` | **Required** | Sets the type of this navbar item to a sidebar's first document. | -| `sidebarId` | `string` | **Required** | The ID of the sidebar that this item is linked to. | -| `label` | `string` | First document link's sidebar label | The name to be shown for this item. | -| `position` | <code>'left' \| 'right'</code> | `'left'` | The side of the navbar this item should appear on. | -| `docsPluginId` | `string` | `'default'` | The ID of the docs plugin that the sidebar belongs to. | - -```mdx-code-block -</APITable> -``` - -:::tip - -Use this navbar item type if your sidebar is updated often and the order is not stable. - -::: - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - // highlight-start - { - type: 'docSidebar', - position: 'left', - sidebarId: 'api', - label: 'API', - }, - // highlight-end - ], - }, - }, -}; -``` - -```js title="sidebars.js" -module.exports = { - tutorial: [ - { - type: 'autogenerated', - dirName: 'guides', - }, - ], - api: [ - // highlight-next-line - 'cli', // The navbar item will be linking to this doc - 'docusaurus-core', - { - type: 'autogenerated', - dirName: 'api', - }, - ], -}; -``` - -#### Navbar docs version dropdown {#navbar-docs-version-dropdown} - -If you use docs with versioning, this special navbar item type that will render a dropdown with all your site's available versions. - -The user will be able to switch from one version to another, while staying on the same doc (as long as the doc ID is constant across versions). - -Accepted fields: - -```mdx-code-block -<APITable name="navbar-docs-version-dropdown"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `type` | `'docsVersionDropdown'` | **Required** | Sets the type of this item to a docs version dropdown. | -| `position` | <code>'left' \| 'right'</code> | `'left'` | The side of the navbar this item should appear on. | -| `dropdownItemsBefore` | <code>[LinkLikeItem](#navbar-dropdown)[]</code> | `[]` | Add additional dropdown items at the beginning of the dropdown. | -| `dropdownItemsAfter` | <code>[LinkLikeItem](#navbar-dropdown)[]</code> | `[]` | Add additional dropdown items at the end of the dropdown. | -| `docsPluginId` | `string` | `'default'` | The ID of the docs plugin that the doc versioning belongs to. | -| `dropdownActiveClassDisabled` | `boolean` | `false` | Do not add the link active class when browsing docs. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - // highlight-start - { - type: 'docsVersionDropdown', - position: 'left', - dropdownItemsAfter: [{to: '/versions', label: 'All versions'}], - dropdownActiveClassDisabled: true, - }, - // highlight-end - ], - }, - }, -}; -``` - -#### Navbar docs version {#navbar-docs-version} - -If you use docs with versioning, this special navbar item type will link to the active/browsed version of your doc (depends on the current URL), and fallback to the latest version. - -Accepted fields: - -```mdx-code-block -<APITable name="navbar-docs-version"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `type` | `'docsVersion'` | **Required** | Sets the type of this item to a doc version link. | -| `label` | `string` | The active/latest version label. | The name to be shown for this item. | -| `to` | `string` | The active/latest version. | The internal link that this item points to. | -| `position` | <code>'left' \| 'right'</code> | `'left'` | The side of the navbar this item should appear on. | -| `docsPluginId` | `string` | `'default'` | The ID of the docs plugin that the doc versioning belongs to. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - // highlight-start - { - type: 'docsVersion', - position: 'left', - to: '/path', - label: 'label', - }, - // highlight-end - ], - }, - }, -}; -``` - -#### Navbar locale dropdown {#navbar-locale-dropdown} - -If you use the [i18n feature](../../i18n/i18n-introduction.md), this special navbar item type will render a dropdown with all your site's available locales. - -The user will be able to switch from one locale to another, while staying on the same page. - -Accepted fields: - -```mdx-code-block -<APITable name="navbar-locale-dropdown"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `type` | `'localeDropdown'` | **Required** | Sets the type of this item to a locale dropdown. | -| `position` | <code>'left' \| 'right'</code> | `'left'` | The side of the navbar this item should appear on. | -| `dropdownItemsBefore` | <code>[LinkLikeItem](#navbar-dropdown)[]</code> | `[]` | Add additional dropdown items at the beginning of the dropdown. | -| `dropdownItemsAfter` | <code>[LinkLikeItem](#navbar-dropdown)[]</code> | `[]` | Add additional dropdown items at the end of the dropdown. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - // highlight-start - { - type: 'localeDropdown', - position: 'left', - dropdownItemsAfter: [ - { - to: 'https://my-site.com/help-us-translate', - label: 'Help us translate', - }, - ], - }, - // highlight-end - ], - }, - }, -}; -``` - -#### Navbar search {#navbar-search} - -If you use the [search](../../search.md), the search bar will be the rightmost element in the navbar. - -However, with this special navbar item type, you can change the default location. - -```mdx-code-block -<APITable name="navbar-search"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `type` | `'search'` | **Required** | Sets the type of this item to a search bar. | -| `position` | <code>'left' \| 'right'</code> | `'left'` | The side of the navbar this item should appear on. | -| `className` | `string` | / | Custom CSS class for this navbar item. | - -```mdx-code-block -</APITable> -``` - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - // highlight-start - { - type: 'search', - position: 'right', - }, - // highlight-end - ], - }, - }, -}; -``` - -#### Navbar with custom HTML {#navbar-with-custom-html} - -You can also render your own HTML markup inside a navbar item using this navbar item type. - -```mdx-code-block -<APITable name="navbar-html"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `type` | `'html'` | **Required** | Sets the type of this item to a HTML element. | -| `position` | <code>'left' \| 'right'</code> | `'left'` | The side of the navbar this item should appear on. | -| `className` | `string` | `''` | Custom CSS class for this navbar item. | -| `value` | `string` | `''` | Custom HTML to be rendered inside this navbar item. | - -```mdx-code-block -</APITable> -``` - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - // highlight-start - { - type: 'html', - position: 'right', - value: '<button>Give feedback</button>', - }, - // highlight-end - ], - }, - }, -}; -``` - -### Auto-hide sticky navbar {#auto-hide-sticky-navbar} - -You can enable this cool UI feature that automatically hides the navbar when a user starts scrolling down the page, and show it again when the user scrolls up. - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - // highlight-next-line - hideOnScroll: true, - }, - }, -}; -``` - -### Navbar style {#navbar-style} - -You can set the static Navbar style without disabling the theme switching ability. The selected style will always apply no matter which theme user have selected. - -Currently, there are two possible style options: `dark` and `primary` (based on the `--ifm-color-primary` color). You can see the styles preview in the [Infima documentation](https://infima.dev/docs/components/navbar/). - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - // highlight-next-line - style: 'primary', - }, - }, -}; -``` - -## CodeBlock {#codeblock} - -Docusaurus uses [Prism React Renderer](https://github.com/FormidableLabs/prism-react-renderer) to highlight code blocks. All configuration are in the `prism` object. - -Accepted fields: - -```mdx-code-block -<APITable name="codeblock"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `theme` | `PrismTheme` | `palenight` | The Prism theme to use for light-theme code blocks. | -| `darkTheme` | `PrismTheme` | `palenight` | The Prism theme to use for dark-theme code blocks. | -| `defaultLanguage` | `string` | `undefined` | The side of the navbar this item should appear on. | -| `magicComments` | `MagicCommentConfig[]` | _see below_ | The list of [magic comments](../../guides/markdown-features/markdown-features-code-blocks.mdx#custom-magic-comments). | - -```mdx-code-block -</APITable> -``` - -```ts -type MagicCommentConfig = { - className: string; - line?: string; - block?: {start: string; end: string}; -}; -``` - -```js -const defaultMagicComments = [ - { - className: 'theme-code-block-highlighted-line', - line: 'highlight-next-line', - block: {start: 'highlight-start', end: 'highlight-end'}, - }, -]; -``` - -### Theme {#theme} - -By default, we use [Palenight](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/themes/palenight.js) as syntax highlighting theme. You can specify a custom theme from the [list of available themes](https://github.com/FormidableLabs/prism-react-renderer/tree/master/src/themes). You may also use a different syntax highlighting theme when the site is in dark mode. - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - prism: { - // highlight-start - theme: require('prism-react-renderer/themes/github'), - darkTheme: require('prism-react-renderer/themes/dracula'), - // highlight-end - }, - }, -}; -``` - -:::note - -If you use the line highlighting Markdown syntax, you might need to specify a different highlight background color for the dark mode syntax highlighting theme. Refer to the [docs for guidance](../../guides/markdown-features/markdown-features-code-blocks.mdx#line-highlighting). - -::: - -### Default language {#default-language} - -You can set a default language for code blocks if no language is added after the opening triple backticks (i.e. ```). Note that a valid [language name](https://prismjs.com/#supported-languages) must be passed. - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - prism: { - // highlight-next-line - defaultLanguage: 'javascript', - }, - }, -}; -``` - -## Footer {#footer-1} - -You can add logo and a copyright to the footer via `themeConfig.footer`. Logo can be placed in [static folder](static-assets.md). Logo URL works in the same way of the navbar logo. - -Accepted fields: - -```mdx-code-block -<APITable name="footer"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `logo` | `Logo` | `undefined` | Customization of the logo object. See [Navbar logo](#navbar-logo) for details. | -| `copyright` | `string` | `undefined` | The copyright message to be displayed at the bottom. | -| `style` | <code>'dark' \| 'light'</code> | `'light'` | The color theme of the footer component. | -| `links` | <code>(Column \| FooterLink)[]</code> | `[]` | The link groups to be present. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - // highlight-start - footer: { - logo: { - alt: 'Meta Open Source Logo', - src: 'img/meta_oss_logo.png', - href: 'https://opensource.fb.com', - width: 160, - height: 51, - }, - copyright: `Copyright © ${new Date().getFullYear()} My Project, Inc. Built with Docusaurus.`, - }, - // highlight-end - }, -}; -``` - -### Footer Links {#footer-links} - -You can add links to the footer via `themeConfig.footer.links`. There are two types of footer configurations: **multi-column footers** and **simple footers**. - -Multi-column footer links have a `title` and a list of `FooterItem`s for each column. - -```mdx-code-block -<APITable name="footer-links"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `title` | `string` | `undefined` | Label of the section of these links. | -| `items` | `FooterItem[]` | `[]` | Links in this section. | - -```mdx-code-block -</APITable> -``` - -Accepted fields of each `FooterItem`: - -```mdx-code-block -<APITable name="footer-items"> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `label` | `string` | **Required** | Text to be displayed for this link. | -| `to` | `string` | **Required** | Client-side routing, used for navigating within the website. The baseUrl will be automatically prepended to this value. | -| `href` | `string` | **Required** | A full-page navigation, used for navigating outside of the website. **Only one of `to` or `href` should be used.** | -| `html` | `string` | `undefined` | Renders the HTML pass-through instead of a simple link. In case `html` is used, no other options should be provided. | - -```mdx-code-block -</APITable> -``` - -Example multi-column configuration: - -```js title="docusaurus.config.js" -module.exports = { - footer: { - // highlight-start - links: [ - { - title: 'Docs', - items: [ - { - label: 'Style Guide', - to: 'docs/', - }, - { - label: 'Second Doc', - to: 'docs/doc2/', - }, - ], - }, - { - title: 'Community', - items: [ - { - label: 'Stack Overflow', - href: 'https://stackoverflow.com/questions/tagged/docusaurus', - }, - { - label: 'Discord', - href: 'https://discordapp.com/invite/docusaurus', - }, - { - label: 'Twitter', - href: 'https://twitter.com/docusaurus', - }, - { - html: ` - <a href="https://www.netlify.com" target="_blank" rel="noreferrer noopener" aria-label="Deploys by Netlify"> - <img src="https://www.netlify.com/img/global/badges/netlify-color-accent.svg" alt="Deploys by Netlify" width="114" height="51" /> - </a> - `, - }, - ], - }, - ], - // highlight-end - }, -}; -``` - -A simple footer just has a list of `FooterItem`s displayed in a row. - -Example simple configuration: - -```js title="docusaurus.config.js" -module.exports = { - footer: { - // highlight-start - links: [ - { - label: 'Stack Overflow', - href: 'https://stackoverflow.com/questions/tagged/docusaurus', - }, - { - label: 'Discord', - href: 'https://discordapp.com/invite/docusaurus', - }, - { - label: 'Twitter', - href: 'https://twitter.com/docusaurus', - }, - { - html: ` - <a href="https://www.netlify.com" target="_blank" rel="noreferrer noopener" aria-label="Deploys by Netlify"> - <img src="https://www.netlify.com/img/global/badges/netlify-color-accent.svg" alt="Deploys by Netlify" width="114" height="51" /> - </a> - `, - }, - ], - // highlight-end - }, -}; -``` - -## Table of Contents {#table-of-contents} - -You can adjust the default table of contents via `themeConfig.tableOfContents`. - -```mdx-code-block -<APITable> -``` - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `minHeadingLevel` | `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. | -| `maxHeadingLevel` | `number` | `3` | Max heading level displayed in the TOC. Should be an integer between 2 and 6. | - -```mdx-code-block -</APITable> -``` - -Example configuration: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - // highlight-start - tableOfContents: { - minHeadingLevel: 2, - maxHeadingLevel: 5, - }, - // highlight-end - }, -}; -``` - -## Hooks {#hooks} - -### `useColorMode` {#use-color-mode} - -A React hook to access the color context. This context contains functions for setting light and dark mode and exposes boolean variable, indicating which mode is currently in use. - -Usage example: - -```jsx -import React from 'react'; -// highlight-next-line -import {useColorMode} from '@docusaurus/theme-common'; - -const Example = () => { - // highlight-next-line - const {colorMode, setColorMode} = useColorMode(); - - return <h1>Dark mode is now {colorMode === 'dark' ? 'on' : 'off'}</h1>; -}; -``` - -:::note - -The component calling `useColorMode` must be a child of the `Layout` component. - -```jsx -function ExamplePage() { - return ( - <Layout> - <Example /> - </Layout> - ); -} -``` - -::: - -## i18n {#i18n} - -Read the [i18n introduction](../../i18n/i18n-introduction.md) first. - -### Translation files location {#translation-files-location} - -- **Base path**: `website/i18n/[locale]/docusaurus-theme-[themeName]` -- **Multi-instance path**: N/A -- **JSON files**: extracted with [`docusaurus write-translations`](../../cli.md#docusaurus-write-translations-sitedir) -- **Markdown files**: N/A - -### Example file-system structure {#example-file-system-structure} - -```bash -website/i18n/[locale]/docusaurus-theme-classic -│ -│ # translations for the theme -├── navbar.json -└── footer.json -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-live-codeblock.md b/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-live-codeblock.md deleted file mode 100644 index be6f4da721d7..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-live-codeblock.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -sidebar_position: 3 -slug: /api/themes/@docusaurus/theme-live-codeblock ---- - -# 📦 theme-live-codeblock - -This theme provides a `@theme/CodeBlock` component that is powered by react-live. You can read more on [interactive code editor](../../guides/markdown-features/markdown-features-code-blocks.mdx#interactive-code-editor) documentation. - -```bash npm2yarn -npm install --save @docusaurus/theme-live-codeblock -``` - -### Configuration {#configuration} - -```js title="docusaurus.config.js" -module.exports = { - plugins: ['@docusaurus/theme-live-codeblock'], - themeConfig: { - liveCodeBlock: { - /** - * The position of the live playground, above or under the editor - * Possible values: "top" | "bottom" - */ - playgroundPosition: 'bottom', - }, - }, -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-search-algolia.md b/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-search-algolia.md deleted file mode 100644 index a7dd47d2a054..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/api/themes/theme-search-algolia.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -sidebar_position: 4 -slug: /api/themes/@docusaurus/theme-search-algolia ---- - -# 📦 theme-search-algolia - -This theme provides a `@theme/SearchBar` component that integrates with Algolia DocSearch easily. Combined with `@docusaurus/theme-classic`, it provides a very easy search integration. You can read more on [search](../../search.md) documentation. - -```bash npm2yarn -npm install --save @docusaurus/theme-search-algolia -``` - -This theme also adds search page available at `/search` (as swizzlable `SearchPage` component) path with OpenSearch support. You can change this default path via `themeConfig.algolia.searchPagePath`. Use `false` to disable search page. - -:::tip - -If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. - -::: diff --git a/website/versioned_docs/version-2.0.0-rc.1/assets/docusaurus-asset-example-banner.png b/website/versioned_docs/version-2.0.0-rc.1/assets/docusaurus-asset-example-banner.png deleted file mode 100644 index ebe95f5ec838..000000000000 Binary files a/website/versioned_docs/version-2.0.0-rc.1/assets/docusaurus-asset-example-banner.png and /dev/null differ diff --git a/website/versioned_docs/version-2.0.0-rc.1/assets/docusaurus-asset-example.docx b/website/versioned_docs/version-2.0.0-rc.1/assets/docusaurus-asset-example.docx deleted file mode 100644 index 3c51aea4e797..000000000000 Binary files a/website/versioned_docs/version-2.0.0-rc.1/assets/docusaurus-asset-example.docx and /dev/null differ diff --git a/website/versioned_docs/version-2.0.0-rc.1/assets/docusaurus-asset-example.xyz b/website/versioned_docs/version-2.0.0-rc.1/assets/docusaurus-asset-example.xyz deleted file mode 100644 index 188262276aa4..000000000000 Binary files a/website/versioned_docs/version-2.0.0-rc.1/assets/docusaurus-asset-example.xyz and /dev/null differ diff --git a/website/versioned_docs/version-2.0.0-rc.1/blog.mdx b/website/versioned_docs/version-2.0.0-rc.1/blog.mdx deleted file mode 100644 index 780a07dbca87..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/blog.mdx +++ /dev/null @@ -1,639 +0,0 @@ ---- -description: Deploy a full-featured blog in no time with Docusaurus. ---- - -# Blog - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -The blog feature enables you to deploy a full-featured blog in no time. - -:::info - -Check the [Blog Plugin API Reference documentation](./api/plugins/plugin-content-blog.md) for an exhaustive list of options. - -::: - -## Initial setup {#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`: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - // ... - navbar: { - items: [ - // ... - // highlight-next-line - {to: 'blog', label: 'Blog', position: 'left'}, // or position: 'right' - ], - }, - }, -}; -``` - -## Adding posts {#adding-posts} - -To publish in the blog, create a Markdown file within the blog directory. - -For example, create a file at `website/blog/2019-09-05-hello-docusaurus-v2.md`: - -```md title="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](./guides/markdown-features/markdown-features-intro.mdx#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](api/plugins/plugin-content-blog.md#markdown-front-matter). - -## Blog list {#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. For example: - -```md ---- -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. You can also add a meta description to the blog list page for better SEO: - -```js title="docusaurus.config.js" -module.exports = { - // ... - presets: [ - [ - '@docusaurus/preset-classic', - { - blog: { - // highlight-start - blogTitle: 'Docusaurus blog!', - blogDescription: 'A Docusaurus powered blog!', - postsPerPage: 'ALL', - // highlight-end - }, - }, - ], - ], -}; -``` - -## Blog sidebar {#blog-sidebar} - -The blog sidebar displays recent blog posts. 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. This will increase the width of the main container. 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": - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - blog: { - // highlight-start - blogSidebarTitle: 'All posts', - blogSidebarCount: 'ALL', - // highlight-end - }, - }, - ], - ], -}; -``` - -## Blog post date {#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`. - -<details> -<summary>Example supported patterns</summary> - -| Pattern | Example | -| --- | --- | -| Single file | `2021-05-28-my-blog-post-title.md` | -| MDX file | `2021-05-28-my-blog-post-title.mdx` | -| Single folder + `index.md` | `2021-05-28-my-blog-post-title/index.md` | -| Folder named by date | `2021-05-28/my-blog-post-title.md` | -| Nested folders by date | `2021/05/28/my-blog-post-title.md` | -| Partially nested folders by date | `2021/05-28-my-blog-post-title.md` | -| Nested folders + `index.md` | `2021/05/28/my-blog-post-title/index.md` | -| Date in the middle of path | `category/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. - -</details> - -:::tip - -Using a folder can be convenient to co-locate blog post images alongside the Markdown file. - -::: - -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: - -```md title="earlier-post.md" ---- -date: 2021-09-13T10:00 ---- -``` - -```md title="later-post.md" ---- -date: 2021-09-13T18:00 ---- -``` - -## Blog post authors {#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 {#inline-authors} - -Blog post authors can be declared directly inside the front matter: - -```mdx-code-block -<Tabs groupId="author-front-matter"> -<TabItem value="single" label="Single author"> -``` - -```md title="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: jimarcey@gmail.com ---- -``` - -```mdx-code-block -</TabItem> -<TabItem value="multiple" label="Multiple authors"> -``` - -```md title="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: jimarcey@gmail.com - - name: Sébastien Lorber - title: Docusaurus maintainer - url: https://sebastienlorber.com - image_url: https://github.com/slorber.png ---- -``` - -```mdx-code-block -</TabItem> -</Tabs> -``` - -:::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: - -```md title="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 {#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: - -```yml title="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: jimarcey@gmail.com - -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: - -```mdx-code-block -<Tabs groupId="author-front-matter"> -<TabItem value="single" label="Single author"> -``` - -```md title="my-blog-post.md" ---- -authors: jmarcey ---- -``` - -```mdx-code-block -</TabItem> -<TabItem value="multiple" label="Multiple authors"> -``` - -```md title="my-blog-post.md" ---- -authors: [jmarcey, slorber] ---- -``` - -```mdx-code-block -</TabItem> -</Tabs> -``` - -:::info - -The `authors` system is very flexible and can suit more advanced use-case: - -<details> - <summary>Mix inline authors and global authors</summary> - -You can use global authors most of the time, and still use inline authors: - -```md title="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 ---- -``` - -</details> - -<details> - <summary>Local override of global authors</summary> - -You can customize the global author's data on per-blog-post basis: - -```md title="my-blog-post.md" ---- -authors: - - key: jmarcey - title: Joel Marcey's new title - - key: slorber - name: Sébastien Lorber's new name ---- -``` - -</details> - -<details> - <summary>Localize the author's configuration file</summary> - -The configuration file can be localized, just create a localized copy of it at: - -```bash -website/i18n/[locale]/docusaurus-plugin-content-blog/authors.yml -``` - -</details> - -::: - -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](/tests/blog/2022/01/20/image-only-authors) for the effect. - -:::caution Feed generation - -[RSS feeds](#feed) require the author's email to be set for the author to appear in the feed. - -::: - -## Reading time {#reading-time} - -Docusaurus generates a reading time estimation for each blog post based on word count. We provide an option to customize this. - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - blog: { - // highlight-start - showReadingTime: true, // When set to false, the "x min read" won't be shown - readingTime: ({content, frontMatter, defaultReadingTime}) => - defaultReadingTime({content, options: {wordsPerMinute: 300}}), - // highlight-end - }, - }, - ], - ], -}; -``` - -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: - -```mdx-code-block -<Tabs> -<TabItem value="disable-per-post" label="Per-post disabling"> -``` - -**Disable reading time on one page:** - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - blog: { - showReadingTime: true, - // highlight-start - readingTime: ({content, frontMatter, defaultReadingTime}) => - frontMatter.hide_reading_time - ? undefined - : defaultReadingTime({content}), - // highlight-end - }, - }, - ], - ], -}; -``` - -Usage: - -```md "my-blog-post.md" ---- -hide_reading_time: true ---- - -This page will no longer display the reading time stats! -``` - -```mdx-code-block -</TabItem> -<TabItem value="passing-options" label="Passing options"> -``` - -**Pass options to the default reading time function:** - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - blog: { - // highlight-start - readingTime: ({content, defaultReadingTime}) => - defaultReadingTime({content, options: {wordsPerMinute: 100}}), - // highlight-end - }, - }, - ], - ], -}; -``` - -```mdx-code-block -</TabItem> -<TabItem value="using-custom-algo" label="Using custom algorithms"> -``` - -**Use a custom implementation of reading time:** - -```js title="docusaurus.config.js" -const myReadingTime = require('./myReadingTime'); - -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - blog: { - // highlight-next-line - readingTime: ({content}) => myReadingTime(content), - }, - }, - ], - ], -}; -``` - -```mdx-code-block -</TabItem> -</Tabs> -``` - -::: - -## Feed {#feed} - -You can generate RSS / Atom / JSON feed by passing `feedOptions`. By default, RSS and Atom feeds are generated. To disable feed generation, set `feedOptions.type` to `null`. - -```ts -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 - }; -}; -``` - -Example usage: - -```js title="docusaurus.config.js" -module.exports = { - // ... - presets: [ - [ - '@docusaurus/preset-classic', - { - blog: { - // highlight-start - feedOptions: { - type: 'all', - copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`, - }, - // highlight-end - }, - }, - ], - ], -}; -``` - -The feeds can be found at: - -<Tabs> -<TabItem value="RSS"> - -```text -https://example.com/blog/rss.xml -``` - -</TabItem> -<TabItem value="Atom"> - -```text -https://example.com/blog/atom.xml -``` - -</TabItem> -<TabItem value="JSON"> - -```text -https://example.com/blog/feed.json -``` - -</TabItem> -</Tabs> - -## Advanced topics {#advanced-topics} - -### Blog-only mode {#blog-only-mode} - -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/`. - -```js title="docusaurus.config.js" -module.exports = { - // ... - presets: [ - [ - '@docusaurus/preset-classic', - { - // highlight-next-line - docs: false, // Optional: disable the docs plugin - blog: { - // highlight-next-line - routeBasePath: '/', // Serve the blog at the site's root - /* other blog options */ - }, - }, - ], - ], -}; -``` - -:::caution - -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! - -::: - -:::tip - -There's also a "Docs-only mode" for those who only want to use the docs. Read [Docs-only mode](./guides/docs/docs-introduction.md) for detailed instructions or a more elaborate explanation of `routeBasePath`. - -::: - -### Multiple blogs {#multiple-blogs} - -By default, the classic theme assumes only one blog per website and hence includes only one instance of the blog plugin. If you would like to have multiple blogs on a single website, it's possible too! 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](./using-plugins.md#multi-instance-plugins-and-plugin-ids), you need to assign a unique ID to the plugins. - -```js title="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](/tests/blog). diff --git a/website/versioned_docs/version-2.0.0-rc.1/browser-support.md b/website/versioned_docs/version-2.0.0-rc.1/browser-support.md deleted file mode 100644 index 404601d8f45e..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/browser-support.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -description: How to keep a reasonable bundle size while ensuring sufficient browser support. ---- - -# Browser support - -Docusaurus allows sites to define the list of supported browsers through a [browserslist configuration](https://github.com/browserslist/browserslist). - -## Purpose {#purpose} - -Websites need to balance between backward compatibility and bundle size. As old browsers do not support modern APIs or syntax, more code is needed to implement the same functionality. - -For example, you may use the [optional chaining syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining): - -```js -const value = obj?.prop?.val; -``` - -...which unfortunately is only recognized by browser versions released after 2020. To be compatible with earlier browser versions, when building your site for production, our JS loader will transpile your code to a more verbose syntax: - -```js -var _obj, _obj$prop; - -const value = - (_obj = obj) === null || _obj === void 0 - ? void 0 - : (_obj$prop = _obj.prop) === null || _obj$prop === void 0 - ? void 0 - : _obj$prop.val; -``` - -However, this penalizes all other users with increased site load time because the 29-character line now becomes 168 characters—a 6-fold increase! (In practice, it will be better because the names used will be shorter.) As a tradeoff, the JS loader only transpiles the syntax to the degree that's supported by all browser versions defined in the browser list. - -The browser list by default is provided through the `package.json` file as a root `browserslist` field. - -:::caution - -On old browsers, the compiled output will use unsupported (too recent) JS syntax, causing React to fail to initialize and end up with a static website with only HTML/CSS and no JS. - -::: - -## Default values {#default-values} - -Websites initialized with the default classic template has the following in `package.json`: - -```json title="package.json" -{ - "name": "docusaurus", - // ... - // highlight-start - "browserslist": { - "production": [">0.5%", "not dead", "not op_mini all"], - "development": [ - "last 1 chrome version", - "last 1 firefox version", - "last 1 safari version" - ] - } - // highlight-end - // ... -} -``` - -Explained in natural language, the browsers supported in production are those: - -- With more than 0.5% of market share; _and_ -- Has official support or updates in the past 24 months (the opposite of "dead"); _and_ -- Is not Opera Mini. - -And browsers used in development are: - -- The latest version of Chrome _or_ Firefox _or_ Safari. - -You can "evaluate" any config with the `browserslist` CLI to obtain the actual list: - -```bash -npx browserslist --env="production" -``` - -The output is all browsers supported in production. Below is the output in January 2022: - -```text -and_chr 96 -and_uc 12.12 -chrome 96 -chrome 95 -chrome 94 -edge 96 -firefox 95 -firefox 94 -ie 11 -ios_saf 15.2 -ios_saf 15.0-15.1 -ios_saf 14.5-14.8 -ios_saf 14.0-14.4 -ios_saf 12.2-12.5 -opera 82 -opera 81 -safari 15.1 -safari 14.1 -safari 13.1 -``` - -## Read more {#read-more} - -You may wish to visit the [browserslist documentation](https://github.com/browserslist/browserslist/blob/main/README.md) for more specifications, especially the accepted [query values](https://github.com/browserslist/browserslist/blob/main/README.md#queries) and [best practices](https://github.com/browserslist/browserslist/blob/main/README.md#best-practices). diff --git a/website/versioned_docs/version-2.0.0-rc.1/cli.md b/website/versioned_docs/version-2.0.0-rc.1/cli.md deleted file mode 100644 index 2f4f68d85cdf..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/cli.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -description: Docusaurus provides a set of scripts to help you generate, serve, and deploy your website. ---- - -# CLI - -Docusaurus provides a set of scripts to help you generate, serve, and deploy your website. - -Once your website is bootstrapped, the website source will contain the Docusaurus scripts that you can invoke with your package manager: - -```json title="package.json" -{ - // ... - "scripts": { - "docusaurus": "docusaurus", - "start": "docusaurus start", - "build": "docusaurus build", - "swizzle": "docusaurus swizzle", - "deploy": "docusaurus deploy", - "clear": "docusaurus clear", - "serve": "docusaurus serve", - "write-translations": "docusaurus write-translations", - "write-heading-ids": "docusaurus write-heading-ids" - } -} -``` - -## Docusaurus CLI commands {#docusaurus-cli-commands} - -Below is a list of Docusaurus CLI commands and their usages: - -### `docusaurus start [siteDir]` {#docusaurus-start-sitedir} - -Builds and serves a preview of your site locally with [Webpack Dev Server](https://webpack.js.org/configuration/dev-server). - -#### Options {#options} - -| Name | Default | Description | -| --- | --- | --- | -| `--port` | `3000` | Specifies the port of the dev server. | -| `--host` | `localhost` | Specify a host to use. For example, if you want your server to be accessible externally, you can use `--host 0.0.0.0`. | -| `--hot-only` | `false` | Enables Hot Module Replacement without page refresh as a fallback in case of build failures. More information [here](https://webpack.js.org/configuration/dev-server/#devserverhotonly). | -| `--no-open` | `false` | Do not open automatically the page in the browser. | -| `--config` | `undefined` | Path to Docusaurus config file, default to `[siteDir]/docusaurus.config.js` | -| `--poll [optionalIntervalMs]` | `false` | Use polling of files rather than watching for live reload as a fallback in environments where watching doesn't work. More information [here](https://webpack.js.org/configuration/watch/#watchoptionspoll). | -| `--no-minify` | `false` | Build website without minimizing JS/CSS bundles. | - -:::important - -Please note that some functionality (for example, anchor links) will not work in development. The functionality will work as expected in production. - -::: - -:::info Development over network - -When forwarding port 3000 from a remote server or VM (e.g. GitHub Codespaces), you can run the dev server on `0.0.0.0` to make it listen on the local IP. - -```bash npm2yarn -npm run start -- --host 0.0.0.0 -``` - -::: - -#### Enabling HTTPS {#enabling-https} - -There are multiple ways to obtain a certificate. We will use [mkcert](https://github.com/FiloSottile/mkcert) as an example. - -1. Run `mkcert localhost` to generate `localhost.pem` + `localhost-key.pem` - -2. Run `mkcert -install` to install the cert in your trust store, and restart your browser - -3. Start the app with Docusaurus HTTPS env variables: - -```bash -HTTPS=true SSL_CRT_FILE=localhost.pem SSL_KEY_FILE=localhost-key.pem yarn start -``` - -4. Open `https://localhost:3000/` - -### `docusaurus build [siteDir]` {#docusaurus-build-sitedir} - -Compiles your site for production. - -#### Options {#options-1} - -| Name | Default | Description | -| --- | --- | --- | -| `--bundle-analyzer` | `false` | Analyze your bundle with the [webpack bundle analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer). | -| `--out-dir` | `build` | The full path for the new output directory, relative to the current workspace. | -| `--config` | `undefined` | Path to Docusaurus config file, default to `[siteDir]/docusaurus.config.js` | -| `--no-minify` | `false` | Build website without minimizing JS/CSS bundles. | - -:::info - -For advanced minification of CSS bundle, we use the [advanced cssnano preset](https://github.com/cssnano/cssnano/tree/master/packages/cssnano-preset-advanced) (along with additional several PostCSS plugins) and [level 2 optimization of clean-css](https://github.com/jakubpawlowicz/clean-css#level-2-optimizations). If as a result of this advanced CSS minification you find broken CSS, build your website with the environment variable `USE_SIMPLE_CSS_MINIFIER=true` to minify CSS with the [default cssnano preset](https://github.com/cssnano/cssnano/tree/master/packages/cssnano-preset-default). **Please [fill out an issue](https://github.com/facebook/docusaurus/issues/new?labels=bug%2C+needs+triage&template=bug.md) if you experience CSS minification bugs.** - -You can skip the HTML minification with the environment variable `SKIP_HTML_MINIFICATION=true`. - -::: - -### `docusaurus swizzle [themeName] [componentName] [siteDir]` {#docusaurus-swizzle} - -[Swizzle](./swizzling.md) a theme component to customize it. - -```bash npm2yarn -npm run swizzle [themeName] [componentName] [siteDir] - -# Example (leaving out the siteDir to indicate this directory) -npm run swizzle @docusaurus/theme-classic Footer -- --eject -``` - -The swizzle CLI is interactive and will guide you through the whole [swizzle process](./swizzling.md). - -#### Options {#options-swizzle} - -| Name | Description | -| --------------- | ---------------------------------------------------- | -| `themeName` | The name of the theme to swizzle from. | -| `componentName` | The name of the theme component to swizzle. | -| `--list` | Display components available for swizzling | -| `--eject` | [Eject](./swizzling.md#ejecting) the theme component | -| `--wrap` | [Wrap](./swizzling.md#wrapping) the theme component | -| `--danger` | Allow immediate swizzling of unsafe components | -| `--typescript` | Swizzle the TypeScript variant component | - -:::caution - -Unsafe components have a higher risk of breaking changes due to internal refactorings. - -::: - -### `docusaurus deploy [siteDir]` {#docusaurus-deploy-sitedir} - -Deploys your site with [GitHub Pages](https://pages.github.com/). Check out the docs on [deployment](deployment.mdx#deploying-to-github-pages) for more details. - -#### Options {#options-3} - -| Name | Default | Description | -| --- | --- | --- | -| `--out-dir` | `build` | The full path for the new output directory, relative to the current workspace. | -| `--skip-build` | `false` | Deploy website without building it. This may be useful when using a custom deploy script. | -| `--config` | `undefined` | Path to Docusaurus config file, default to `[siteDir]/docusaurus.config.js` | - -### `docusaurus serve [siteDir]` {#docusaurus-serve-sitedir} - -Serve your built website locally. - -| Name | Default | Description | -| --- | --- | --- | -| `--port` | `3000` | Use specified port | -| `--dir` | `build` | The full path for the output directory, relative to the current workspace | -| `--build` | `false` | Build website before serving | -| `--config` | `undefined` | Path to Docusaurus config file, default to `[siteDir]/docusaurus.config.js` | -| `--host` | `localhost` | Specify a host to use. For example, if you want your server to be accessible externally, you can use `--host 0.0.0.0`. | -| `--no-open` | `false` locally, `true` in CI | Do not open a browser window to the server location. | - -### `docusaurus clear [siteDir]` {#docusaurus-clear-sitedir} - -Clear a Docusaurus site's generated assets, caches, build artifacts. - -We recommend running this command before reporting bugs, after upgrading versions, or anytime you have issues with your Docusaurus site. - -### `docusaurus write-translations [siteDir]` {#docusaurus-write-translations-sitedir} - -Write the JSON translation files that you will have to translate. - -By default, the files are written in `website/i18n/<defaultLocale>/...`. - -| Name | Default | Description | -| --- | --- | --- | -| `--locale` | `<defaultLocale>` | Define which locale folder you want to write translations the JSON files in | -| `--override` | `false` | Override existing translation messages | -| `--config` | `undefined` | Path to Docusaurus config file, default to `[siteDir]/docusaurus.config.js` | -| `--messagePrefix` | `''` | Allows adding a prefix to each translation message, to help you highlight untranslated strings | - -### `docusaurus write-heading-ids [siteDir] [files]` {#docusaurus-write-heading-ids-sitedir} - -Add [explicit heading IDs](./guides/markdown-features/markdown-features-toc.mdx#explicit-ids) to the Markdown documents of your site. - -| Name | Default | Description | -| --- | --- | --- | -| `files` | All MD files used by plugins | The files that you want heading IDs to be written to. | -| `--maintain-case` | `false` | Keep the headings' casing, otherwise make all lowercase. | -| `--overwrite` | `false` | Overwrite existing heading IDs. | diff --git a/website/versioned_docs/version-2.0.0-rc.1/configuration.md b/website/versioned_docs/version-2.0.0-rc.1/configuration.md deleted file mode 100644 index eb192c6f9201..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/configuration.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -description: Configuring your site's behavior through docusaurus.config.js and more. ---- - -# Configuration - -import TOCInline from '@theme/TOCInline'; - -Docusaurus has a unique take on configurations. We encourage you to congregate information about your site into one place. We guard the fields of this file and facilitate making this data object accessible across your site. - -Keeping a well-maintained `docusaurus.config.js` helps you, your collaborators, and your open source contributors to be able to focus on documentation while still being able to customize the site. - -## What goes into a `docusaurus.config.js`? {#what-goes-into-a-docusaurusconfigjs} - -You should not have to write your `docusaurus.config.js` from scratch even if you are developing your site. All templates come with a `docusaurus.config.js` that includes defaults for the common options. - -However, it can be helpful if you have a high-level understanding of how the configurations are designed and implemented. - -The high-level overview of Docusaurus configuration can be categorized into: - -<TOCInline toc={toc} minHeadingLevel={3} maxHeadingLevel={3} /> - -For exact reference to each of the configurable fields, you may refer to [**`docusaurus.config.js` API reference**](api/docusaurus.config.js.md). - -### Site metadata {#site-metadata} - -Site metadata contains the essential global metadata such as `title`, `url`, `baseUrl`, and `favicon`. - -They are used in several places such as your site's title and headings, browser tab icon, social sharing (Facebook, Twitter) information or even to generate the correct path to serve your static files. - -### Deployment configurations {#deployment-configurations} - -Deployment configurations such as `projectName`, `organizationName`, and optionally `deploymentBranch` are used when you deploy your site with the `deploy` command. - -It is recommended to check the [deployment docs](deployment.mdx) for more information. - -### Theme, plugin, and preset configurations {#theme-plugin-and-preset-configurations} - -List the [themes](./using-plugins.md#using-themes), [plugins](./using-plugins.md), and [presets](./using-plugins.md#using-presets) for your site in the `themes`, `plugins`, and `presets` fields, respectively. These are typically npm packages: - -```js title="docusaurus.config.js" -module.exports = { - // ... - plugins: [ - '@docusaurus/plugin-content-blog', - '@docusaurus/plugin-content-pages', - ], - themes: ['@docusaurus/theme-classic'], -}; -``` - -:::tip - -Docusaurus supports [**module shorthands**](./using-plugins.md#module-shorthands), allowing you to simplify the above configuration as: - -```js title="docusaurus.config.js" -module.exports = { - // ... - plugins: ['content-blog', 'content-pages'], - themes: ['classic'], -}; -``` - -::: - -They can also be loaded from local directories: - -```js title="docusaurus.config.js" -const path = require('path'); - -module.exports = { - // ... - themes: [path.resolve(__dirname, '/path/to/docusaurus-local-theme')], -}; -``` - -To specify options for a plugin or theme, replace the name of the plugin or theme in the config file with an array containing the name and an options object: - -```js title="docusaurus.config.js" -module.exports = { - // ... - plugins: [ - [ - 'content-blog', - { - path: 'blog', - routeBasePath: 'blog', - include: ['*.md', '*.mdx'], - // ... - }, - ], - 'content-pages', - ], -}; -``` - -To specify options for a plugin or theme that is bundled in a preset, pass the options through the `presets` field. In this example, `docs` refers to `@docusaurus/plugin-content-docs` and `theme` refers to `@docusaurus/theme-classic`. - -```js title="docusaurus.config.js" -module.exports = { - // ... - presets: [ - [ - '@docusaurus/preset-classic', - { - docs: { - sidebarPath: require.resolve('./sidebars.js'), - }, - theme: { - customCss: [require.resolve('./src/css/custom.css')], - }, - }, - ], - ], -}; -``` - -:::tip - -The `presets: [['classic', {...}]]` shorthand works as well. - -::: - -For further help configuring themes, plugins, and presets, see [Using Plugins](./using-plugins.md). - -### Custom configurations {#custom-configurations} - -Docusaurus guards `docusaurus.config.js` from unknown fields. To add custom fields, define them in `customFields`. - -Example: - -```js title="docusaurus.config.js" -module.exports = { - // ... - // highlight-start - customFields: { - image: '', - keywords: [], - }, - // highlight-end - // ... -}; -``` - -## Accessing configuration from components {#accessing-configuration-from-components} - -Your configuration object will be made available to all the components of your site. And you may access them via React context as `siteConfig`. - -Basic example: - -```jsx -import React from 'react'; -// highlight-next-line -import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; - -const Hello = () => { - // highlight-start - const {siteConfig} = useDocusaurusContext(); - // highlight-end - const {title, tagline} = siteConfig; - - return <div>{`${title} · ${tagline}`}</div>; -}; -``` - -:::tip - -If you just want to use those fields on the client side, you could create your own JS files and import them as ES6 modules, there is no need to put them in `docusaurus.config.js`. - -::: - -## Customizing Babel Configuration {#customizing-babel-configuration} - -For new Docusaurus projects, we automatically generated a `babel.config.js` in the project root. - -```js title="babel.config.js" -module.exports = { - presets: [require.resolve('@docusaurus/core/lib/babel/preset')], -}; -``` - -Most of the time, this configuration will work just fine. If you want to customize your Babel configuration (e.g. to add support for Flow), you can directly edit this file. For your changes to take effect, you need to restart the Docusaurus dev server. diff --git a/website/versioned_docs/version-2.0.0-rc.1/deployment.mdx b/website/versioned_docs/version-2.0.0-rc.1/deployment.mdx deleted file mode 100644 index 642530ea69eb..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/deployment.mdx +++ /dev/null @@ -1,809 +0,0 @@ ---- -description: Deploy your Docusaurus app for production on a range of static site hosting services. ---- - -# Deployment - -To build the static files of your website for production, run: - -```bash npm2yarn -npm run build -``` - -Once it finishes, the static files will be generated within the `build` directory. - -:::note - -The only responsibility of Docusaurus is to build your site and emit static files in `build`. - -It is now up to you to choose how to host those static files. - -::: - -You can deploy your site to static site hosting services such as [Vercel](https://vercel.com/), [GitHub Pages](https://pages.github.com/), [Netlify](https://www.netlify.com/), [Render](https://render.com/docs/static-sites), [Surge](https://surge.sh/help/getting-started-with-surge)... - -A Docusaurus site is statically rendered, and it can generally work without JavaScript! - -## Configuration {#configuration} - -The following parameters are required in `docusaurus.config.js` to optimize routing and serve files from the correct location: - -| Name | Description | -| --- | --- | -| `url` | URL for your site. For a site deployed at `https://my-org.com/my-project/`, `url` is `https://my-org.com/`. | -| `baseUrl` | Base URL for your project, with a trailing slash. For a site deployed at `https://my-org.com/my-project/`, `baseUrl` is `/my-project/`. | - -## Testing your Build Locally {#testing-build-locally} - -It is important to test your build locally before deploying it for production. Docusaurus provides a [`docusaurus serve`](cli.md#docusaurus-serve-sitedir) command for that: - -```bash npm2yarn -npm run serve -``` - -By default, this will load your site at [http://localhost:3000/](http://localhost:3000/). - -## Trailing slash configuration {#trailing-slashes} - -Docusaurus has a [`trailingSlash` config](./api/docusaurus.config.js.md#trailingSlash), to allow customizing URLs/links and emitted filename patterns. - -The default value generally works fine. Unfortunately, each static hosting provider has a **different behavior**, and deploying the exact same site to various hosts can lead to distinct results. Depending on your host, it can be useful to change this config. - -:::tip - -Use [slorber/trailing-slash-guide](https://github.com/slorber/trailing-slash-guide) to understand better the behavior of your host and configure `trailingSlash` appropriately. - -::: - -## Using environment variables {#using-environment-variables} - -Putting potentially sensitive information in the environment is common practice. However, in a typical Docusaurus website, the `docusaurus.config.js` file is the only interface to the Node.js environment (see [our architecture overview](advanced/architecture.md)), while everything else—MDX pages, React components... are client side and do not have direct access to the `process` global. In this case, you can consider using [`customFields`](api/docusaurus.config.js.md#customFields) to pass environment variables to the client side. - -```js title="docusaurus.config.js" -// If you are using dotenv (https://www.npmjs.com/package/dotenv) -require('dotenv').config(); - -module.exports = { - title: '...', - url: process.env.URL, // You can use environment variables to control site specifics as well - // highlight-start - customFields: { - // Put your custom environment here - teamEmail: process.env.EMAIL, - }, - // highlight-end -}; -``` - -```jsx title="home.jsx" -import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; - -export default function Home() { - const { - siteConfig: {customFields}, - } = useDocusaurusContext(); - return <div>Contact us through {customFields.teamEmail}!</div>; -} -``` - -## Choosing a hosting provider {#choosing-a-hosting-provider} - -There are a few common hosting options: - -- [Self hosting](#self-hosting) with an HTTP server like Apache2 or Nginx; -- Jamstack providers, e.g. [Netlify](#deploying-to-netlify) and [Vercel](#deploying-to-vercel). We will use them as references, but the same reasoning can apply to other providers. -- [GitHub Pages](#deploying-to-github-pages). (By definition, it is also Jamstack, but we compare it separately.) - -If you are unsure of which one to choose, ask the following questions: - -<details> - -<summary> - How much resource (person-hours, money) am I willing to invest in this? -</summary> - -- 🔴 Self-hosting is the hardest to set up—you would usually need an experienced person to manage this. Cloud services are almost never free, and setting up an on-site server and connecting it to the WAN can be even more costly. -- 🟢 Jamstack providers can help you set up a working website in almost no time and offers features like server-side redirects that are easily configurable. Many providers offer generous build time quotas even for free plans that you would almost never exceed. However, it's still ultimately limited—you would need to pay once you hit the limit. Check the pricing page of your provider for details. -- 🟡 The GitHub Pages deployment workflow can be tedious to set up. (Evidence: see the length of [Deploying to GitHub Pages](#deploying-to-github-pages)!) However, this service (including build and deployment) is always free for public repositories, and we have detailed instructions to help you make it work. - -</details> - -<details> - -<summary>How much server-side configuration would I need?</summary> - -- 🟢 With self-hosting, you have access to the entire server's configuration. You can configure the virtual host to serve different content based on the request URL; you can do complicated server-side redirects; you can put part of the site behind authentication... If you need a lot of server-side features, self-host your website. -- 🟡 Jamstack usually offers some server-side configurations, e.g. URLs formatting (trailing slashes), server-side redirects... -- 🔴 GitHub Pages doesn't expose server-side configurations besides enforcing HTTPS and setting CNAME. - -</details> - -<details> - -<summary>Do I have needs to cooperate?</summary> - -- 🟡 Self-hosted services can achieve the same effect as Netlify, but with much more heavy-lifting. Usually, you would have a specific person who looks after the deployment, and the workflow won't be very git-based as opposed to the other two options. -- 🟢 Netlify and Vercel have deploy previews for every pull request, which is useful for a team to review work before merging to production. You can also manage a team with different member access to the deployment. -- 🟡 GitHub Pages cannot do deploy previews in a non-convoluted way. One repo can only be associated with one site deployment. On the other hand, you can control who has write access to the site's deployment. - -</details> - -There isn't a silver bullet. You need to weigh your needs and resources before making a choice. - -## Self-Hosting {#self-hosting} - -Docusaurus can be self-hosted using [`docusaurus serve`](cli.md#docusaurus-serve-sitedir). Change port using `--port` and `--host` to change host. - -```bash npm2yarn -npm run serve -- --build --port 80 --host 0.0.0.0 -``` - -:::warning - -It is not the best option, compared to a static hosting provider / CDN. - -::: - -:::warning - -In the following sections, we will introduce a few common hosting providers and how they should be configured to deploy Docusaurus sites most efficiently. Some of the writeups are provided by external contributors. Docusaurus is not interest-related with any of the services. The documentation may not be up-to-date: recent changes in their API may not be reflected on our side. If you see outdated content, PRs are welcome. - -For the same concern of up-to-datedness, we have stopped accepting PRs adding new hosting options. You can, however, publish your writeup on a separate site (e.g. your blog, or the provider's official website), and ask us to include a link to your writeup. - -::: - -## Deploying to Netlify {#deploying-to-netlify} - -To deploy your Docusaurus 2 sites to [Netlify](https://www.netlify.com/), first make sure the following options are properly configured: - -```js title="docusaurus.config.js" -module.exports = { - // highlight-start - url: 'https://docusaurus-2.netlify.app', // Url to your site with no trailing slash - baseUrl: '/', // Base directory of your site relative to your repo - // highlight-end - // ... -}; -``` - -Then, [create your site with Netlify](https://app.netlify.com/start). - -While you set up the site, specify the build commands and directories as follows: - -- build command: `npm run build` -- publish directory: `build` - -If you did not configure these build options, you may still go to "Site settings" -> "Build & deploy" after your site is created. - -Once properly configured with the above options, your site should deploy and automatically redeploy upon merging to your deploy branch, which defaults to `main`. - -:::caution - -Some Docusaurus sites put the `docs` folder outside of `website` (most likely former Docusaurus v1 sites): - -```bash -repo # git root -├── docs # MD files -└── website # Docusaurus root -``` - -If you decide to use the `website` folder as Netlify's base directory, Netlify will not trigger builds when you update the `docs` folder, and you need to configure a [custom `ignore` command](https://docs.netlify.com/configure-builds/common-configurations/ignore-builds/): - -```toml title="website/netlify.toml" -[build] - ignore = "git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF . ../docs/" -``` - -::: - -:::warning - -By default, Netlify adds trailing slashes to Docusaurus URLs. - -It is recommended to disable the Netlify setting `Post Processing > Asset Optimization > Pretty Urls` to prevent lowercased URLs, unnecessary redirects, and 404 errors. - -**Be very careful**: the `Disable asset optimization` global checkbox is broken and does not really disable the `Pretty URLs` setting in practice. Please make sure to **uncheck it independently**. - -If you want to keep the `Pretty Urls` Netlify setting on, adjust the `trailingSlash` Docusaurus config appropriately. - -Refer to [slorber/trailing-slash-guide](https://github.com/slorber/trailing-slash-guide) for more information. - -::: - -## Deploying to Vercel {#deploying-to-vercel} - -Deploying your Docusaurus project to [Vercel](https://vercel.com/) will provide you with [various benefits](https://vercel.com/) in the areas of performance and ease of use. - -To deploy your Docusaurus project with a [Vercel for Git Integration](https://vercel.com/docs/concepts/git), make sure it has been pushed to a Git repository. - -Import the project into Vercel using the [Import Flow](https://vercel.com/import/git). During the import, you will find all relevant options preconfigured for you; however, you can choose to change any of these options, a list of which can be found [here](https://vercel.com/docs/build-step#build-&-development-settings). - -After your project has been imported, all subsequent pushes to branches will generate [Preview Deployments](https://vercel.com/docs/platform/deployments#preview), and all changes made to the [Production Branch](https://vercel.com/docs/git-integrations#production-branch) (usually "main" or "master") will result in a [Production Deployment](https://vercel.com/docs/platform/deployments#production). - -## Deploying to GitHub Pages {#deploying-to-github-pages} - -Docusaurus provides an easy way to publish to [GitHub Pages](https://pages.github.com/), which comes for free with every GitHub repository. - -### Overview {#github-pages-overview} - -Usually, there are two repositories (at least, two branches) involved in a publishing process: the branch containing the source files, and the branch containing the build output to be served with GitHub Pages. In the following tutorial, they will be referred to as **"source"** and **"deployment"**, respectively. - -Each GitHub repository is associated with a GitHub Pages service. If the deployment repository is called `my-org/my-project` (where `my-org` is the organization name or username), the deployed site will appear at `https://my-org.github.io/my-project/`. Specially, if the deployment repository is called `my-org/my-org.github.io` (the _organization GitHub Pages repo_), the site will appear at `https://my-org.github.io/`. - -:::info - -In case you want to use your custom domain for GitHub Pages, create a `CNAME` file in the `static` directory. Anything within the `static` directory will be copied to the root of the `build` directory for deployment. When using a custom domain, you should be able to move back from `baseUrl: '/projectName/'` to `baseUrl: '/'`, and also set your `url` to your custom domain. - -You may refer to GitHub Pages' documentation [User, Organization, and Project Pages](https://help.github.com/en/articles/user-organization-and-project-pages) for more details. - -::: - -GitHub Pages picks up deploy-ready files (the output from `docusaurus build`) from the default branch (`master` / `main`, usually) or the `gh-pages` branch, and either from the root or the `/docs` folder. You can configure that through `Settings > Pages` in your repository. This branch will be called the "deployment branch". - -We provide a `docusaurus deploy` command that helps you deploy your site from the source branch to the deployment branch in one command: clone, build, and commit. - -### `docusaurus.config.js` settings {#docusaurusconfigjs-settings} - -First, modify your `docusaurus.config.js` and add the following params: - -| Name | Description | -| --- | --- | -| `organizationName` | The GitHub user or organization that owns the deployment repository. | -| `projectName` | The name of the deployment repository. | -| `deploymentBranch` | The name of deployment branch. Defaults to `'gh-pages'` for non-organization GitHub Pages repos (`projectName` not ending in `.github.io`). Otherwise, this needs to be explicit as a config field or environment variable. | - -These fields also have their environment variable counterparts, which have a higher priority: `ORGANIZATION_NAME`, `PROJECT_NAME`, and `DEPLOYMENT_BRANCH`. - -:::caution - -GitHub Pages adds a trailing slash to Docusaurus URLs by default. It is recommended to set a `trailingSlash` config (`true` or `false`, not `undefined`). - -::: - -Example: - -```js title="docusaurus.config.js" -module.exports = { - // ... - url: 'https://endiliey.github.io', // Your website URL - baseUrl: '/', - // highlight-start - projectName: 'endiliey.github.io', - organizationName: 'endiliey', - trailingSlash: false, - // highlight-end - // ... -}; -``` - -:::warning - -By default, GitHub Pages runs published files through [Jekyll](https://jekyllrb.com/). Since Jekyll will discard any files that begin with `_`, it is recommended that you disable Jekyll by adding an empty file named `.nojekyll` file to your `static` directory. - -::: - -### Environment settings {#environment-settings} - -| Name | Description | -| --- | --- | -| `USE_SSH` | Set to `true` to use SSH instead of the default HTTPS for the connection to the GitHub repo. If the source repo URL is an SSH URL (e.g. `git@github.com:facebook/docusaurus.git`), `USE_SSH` is inferred to be `true`. | -| `GIT_USER` | The username for a GitHub account that **has push access to the deployment repo**. For your own repositories, this will usually be your GitHub username. Required if not using SSH, and ignored otherwise. | -| `GIT_PASS` | Personal access token of the git user (specified by `GIT_USER`), to facilitate non-interactive deployment (e.g. continuous deployment) | -| `CURRENT_BRANCH` | The source branch. Usually, the branch will be `main` or `master`, but it could be any branch except for `gh-pages`. If nothing is set for this variable, then the current branch from which `docusaurus deploy` is invoked will be used. | - -GitHub enterprise installations should work in the same manner as github.com; you only need to set the organization's GitHub Enterprise host as an environment variable: - -| Name | Description | -| ------------- | ----------------------------------------------- | -| `GITHUB_HOST` | The domain name of your GitHub enterprise site. | -| `GITHUB_PORT` | The port of your GitHub enterprise site. | - -### Deploy {#deploy} - -Finally, to deploy your site to GitHub Pages, run: - -```mdx-code-block -<Tabs> -<TabItem value="bash" label="Bash"> -``` - -```bash -GIT_USER=<GITHUB_USERNAME> yarn deploy -``` - -```mdx-code-block -</TabItem> -<TabItem value="windows" label="Windows"> -``` - -```batch -cmd /C "set "GIT_USER=<GITHUB_USERNAME>" && yarn deploy" -``` - -````mdx-code-block -</TabItem> -<TabItem value="powershell" label="PowerShell"> -```mdx-code-block - -```powershell -cmd /C 'set "GIT_USER=<GITHUB_USERNAME>" && yarn deploy' -```` - -```mdx-code-block -</TabItem> -</Tabs> -``` - -:::caution - -Beginning in August 2021, GitHub requires every command-line sign-in to use the **personal access token** instead of the password. When GitHub prompts for your password, enter the PAT instead. See the [GitHub documentation](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) for more information. - -Alternatively, you can use SSH (`USE_SSH=true`) to log in. - -::: - -### Triggering deployment with GitHub Actions {#triggering-deployment-with-github-actions} - -[GitHub Actions](https://help.github.com/en/actions) allow you to automate, customize, and execute your software development workflows right in your repository. - -The workflow examples below assume your website source resides in the `main` branch of your repository (the _source branch_ is `main`), and your [publishing source](https://help.github.com/en/github/working-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site) is configured for the `gh-pages` branch (the _deployment branch_ is `gh-pages`). - -Our goal is that: - -1. When a new pull request is made to `main`, there's an action that ensures the site builds successfully, without actually deploying. This job will be called `test-deploy`. -2. When a pull request is merged to the `main` branch or someone pushes to the `main` branch directly, it will be built and deployed to the `gh-pages` branch. After that, the new build output will be served on the GitHub Pages site. This job will be called `deploy`. - -Here are two approaches to deploying your docs with GitHub Actions. Based on the location of your deployment branch (`gh-pages`), choose the relevant tab below: - -- Source repo and deployment repo are the **same** repository. -- The deployment repo is a **remote** repository, different from the source. - -```mdx-code-block -<Tabs> -<TabItem value="same" label="Same"> -``` - -While you can have both jobs defined in the same workflow file, the original `deploy` workflow will always be listed as skipped in the PR check suite status, which is not communicative of the actual status and provides no value to the review process. We therefore propose to manage them as separate workflows instead. - -We will use a popular third-party deployment action: [peaceiris/actions-gh-pages](https://github.com/peaceiris/actions-gh-pages#%EF%B8%8F-docusaurus). - -<details> -<summary>GitHub action files</summary> - -Add these two workflow files: - -:::warning Tweak the parameters for your setup - -These files assume you are using Yarn. If you use npm, change `cache: yarn`, `yarn install --frozen-lockfile`, `yarn build` to `cache: npm`, `npm ci`, `npm run build` accordingly. - -If your Docusaurus project is not at the root of your repo, you may need to configure a [default working directory](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#example-set-the-default-shell-and-working-directory), and adjust the paths accordingly. - -::: - -```yml title=".github/workflows/deploy.yml" -name: Deploy to GitHub Pages - -on: - push: - branches: - - main - # Review gh actions docs if you want to further define triggers, paths, etc - # https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on - -jobs: - deploy: - name: Deploy to GitHub Pages - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v3 - with: - node-version: 18 - cache: yarn - - - name: Install dependencies - run: yarn install --frozen-lockfile - - name: Build website - run: yarn build - - # Popular action to deploy to GitHub Pages: - # Docs: https://github.com/peaceiris/actions-gh-pages#%EF%B8%8F-docusaurus - - name: Deploy to GitHub Pages - uses: peaceiris/actions-gh-pages@v3 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - # Build output to publish to the `gh-pages` branch: - publish_dir: ./build - # The following lines assign commit authorship to the official - # GH-Actions bot for deploys to `gh-pages` branch: - # https://github.com/actions/checkout/issues/13#issuecomment-724415212 - # The GH actions bot is used by default if you didn't specify the two fields. - # You can swap them out with your own user credentials. - user_name: github-actions[bot] - user_email: 41898282+github-actions[bot]@users.noreply.github.com -``` - -```yml title=".github/workflows/test-deploy.yml" -name: Test deployment - -on: - pull_request: - branches: - - main - # Review gh actions docs if you want to further define triggers, paths, etc - # https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on - -jobs: - test-deploy: - name: Test deployment - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v3 - with: - node-version: 18 - cache: yarn - - - name: Install dependencies - run: yarn install --frozen-lockfile - - name: Test build website - run: yarn build -``` - -</details> - -```mdx-code-block -</TabItem> -<TabItem value="remote" label="Remote"> -``` - -A cross-repo publish is more difficult to set up, because you need to push to another repo with permission checks. We will be using SSH to do the authentication. - -1. Generate a new [SSH key](https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent). Since this SSH key will be used in CI, make sure to not enter any passphrase. -2. By default, your public key should have been created in `~/.ssh/id_rsa.pub`; otherwise, use the name you've provided in the previous step to add your key to [GitHub deploy keys](https://developer.github.com/v3/guides/managing-deploy-keys/). -3. Copy the key to clipboard with `pbcopy < ~/.ssh/id_rsa.pub` and paste it as a [deploy key](https://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys) in the deployment repository. Copy the file content if the command line doesn't work for you. Check the box for `Allow write access` before saving your deployment key. -4. You'll need your private key as a [GitHub secret](https://help.github.com/en/actions/configuring-and-managing-workflows/creating-and-storing-encrypted-secrets) to allow Docusaurus to run the deployment for you. -5. Copy your private key with `pbcopy < ~/.ssh/id_rsa` and paste a GitHub secret with the name `GH_PAGES_DEPLOY` on your source repository. Copy the file content if the command line doesn't work for you. Save your secret. -6. Create your [documentation workflow file](https://help.github.com/en/actions/configuring-and-managing-workflows/configuring-a-workflow#creating-a-workflow-file) in `.github/workflows/`. In this example it's `deploy.yml`. -7. You should have essentially: the source repo with the GitHub workflow set with the private SSH key as GitHub Secret and your deployment repo set with the public SSH key in GitHub Deploy Keys. - -<details> - -<summary>GitHub action file</summary> - -:::warning - -Please make sure that you replace `actions@github.com` with your GitHub email and `gh-actions` with your name. - -This file assumes you are using Yarn. If you use npm, change `cache: yarn`, `yarn install --frozen-lockfile`, `yarn build` to `cache: npm`, `npm ci`, `npm run build` accordingly. - -::: - -```yml title=".github/workflows/deploy.yml" -name: Deploy to GitHub Pages - -on: - pull_request: - branches: [main] - push: - branches: [main] - -jobs: - test-deploy: - if: github.event_name != 'push' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v3 - with: - node-version: 18 - cache: yarn - - name: Install dependencies - run: yarn install --frozen-lockfile - - name: Test build website - run: yarn build - deploy: - if: github.event_name != 'pull_request' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v3 - with: - node-version: 18 - cache: yarn - - uses: webfactory/ssh-agent@v0.5.0 - with: - ssh-private-key: ${{ secrets.GH_PAGES_DEPLOY }} - - name: Deploy to GitHub Pages - env: - USE_SSH: true - run: | - git config --global user.email "actions@github.com" - git config --global user.name "gh-actions" - yarn install --frozen-lockfile - yarn deploy -``` - -</details> - -```mdx-code-block -</TabItem> -</Tabs> -``` - -<details> - -<summary>Site not deployed properly?</summary> - -After pushing to main, if you don't see your site published at the desired location (for example, it says "There isn't a GitHub Pages site here", or it's showing your repo's README.md file), check the following: - -- It may take a few minutes for GitHub pages to pick up the new files, so wait for about 3 minutes and refresh before concluding it isn't working. -- On your repo's landing page, you should see a little green tick next to the last commit's title, indicating the CI has passed. If you see a cross, it means the build or deployment failed, and you should check the log for more debugging information. -- Click on the tick and make sure your see a "Deploy to GitHub Pages" workflow. Names like "pages build and deployment / deploy" are GitHub's default workflows, indicating your custom deployment workflow failed to be triggered at all. Make sure the YAML files are put under the `.github/workflows` folder, and the trigger condition is set correctly (for example, if your default branch is "master" instead of "main", you need to change the `on.push` property). -- We are using `gh-pages` as the deployment branch. Under your repo's Settings > Pages, make sure the "Source" (which is the source for the _deployment_ files, not "source" as in our terminology) is set to "gh-pages" + "/ (root)". -- If you are using a custom domain, make sure the DNS record is pointing to the GitHub pages servers' IP. - -</details> - -### Triggering deployment with Travis CI {#triggering-deployment-with-travis-ci} - -Continuous integration (CI) services are typically used to perform routine tasks whenever new commits are checked in to source control. These tasks can be any combination of running unit tests and integration tests, automating builds, publishing packages to npm, and deploying changes to your website. All you need to do to automate the deployment of your website is to invoke the `yarn deploy` script whenever your website is updated. The following section covers how to do just that using [Travis CI](https://travis-ci.com/), a popular continuous integration service provider. - -1. Go to https://github.com/settings/tokens and generate a new [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/). When creating the token, grant it the `repo` scope so that it has the permissions it needs. -2. Using your GitHub account, [add the Travis CI app](https://github.com/marketplace/travis-ci) to the repository you want to activate. -3. Open your Travis CI dashboard. The URL looks like `https://travis-ci.com/USERNAME/REPO`, and navigate to the `More options > Setting > Environment Variables` section of your repository. -4. Create a new environment variable named `GH_TOKEN` with your newly generated token as its value, then `GH_EMAIL` (your email address) and `GH_NAME` (your GitHub username). -5. Create a `.travis.yml` on the root of your repository with the following: - -```yml title=".travis.yml" -language: node_js -node_js: - - 18 -branches: - only: - - main -cache: - yarn: true -script: - - git config --global user.name "${GH_NAME}" - - git config --global user.email "${GH_EMAIL}" - - echo "machine github.com login ${GH_NAME} password ${GH_TOKEN}" > ~/.netrc - - yarn install - - GIT_USER="${GH_NAME}" yarn deploy -``` - -Now, whenever a new commit lands in `main`, Travis CI will run your suite of tests and if everything passes, your website will be deployed via the `yarn deploy` script. - -### Triggering deployment with Buddy {#triggering-deployment-with-buddy} - -[Buddy](https://buddy.works/) is an easy-to-use CI/CD tool that allows you to automate the deployment of your portal to different environments, including GitHub Pages. - -Follow these steps to create a pipeline that automatically deploys a new version of your website whenever you push changes to the selected branch of your project: - -1. Go to https://github.com/settings/tokens and generate a new [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/). When creating the token, grant it the `repo` scope so that it has the permissions it needs. -2. Sign in to your Buddy account and create a new project. -3. Choose GitHub as your git hosting provider and select the repository with the code of your website. -4. Using the left navigation panel, switch to the `Pipelines` view. -5. Create a new pipeline. Define its name, set the trigger mode to `On push`, and select the branch that triggers the pipeline execution. -6. Add a `Node.js` action. -7. Add these commands in the action's terminal: - -```bash -GIT_USER=<GH_PERSONAL_ACCESS_TOKEN> -git config --global user.email "<YOUR_GH_EMAIL>" -git config --global user.name "<YOUR_GH_USERNAME>" -yarn deploy -``` - -After creating this simple pipeline, each new commit pushed to the branch you selected deploys your website to GitHub Pages using `yarn deploy`. Read [this guide](https://buddy.works/guides/react-docusaurus) to learn more about setting up a CI/CD pipeline for Docusaurus. - -### Using Azure Pipelines {#using-azure-pipelines} - -1. Sign Up at [Azure Pipelines](https://azure.microsoft.com/en-us/services/devops/pipelines/) if you haven't already. -2. Create an organization. Within the organization, create a project and connect your repository from GitHub. -3. Go to https://github.com/settings/tokens and generate a new [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/) with the `repo` scope. -4. In the project page (which looks like `https://dev.azure.com/ORG_NAME/REPO_NAME/_build`), create a new pipeline with the following text. Also, click on edit and add a new environment variable named `GH_TOKEN` with your newly generated token as its value, then `GH_EMAIL` (your email address) and `GH_NAME` (your GitHub username). Make sure to mark them as secret. Alternatively, you can also add a file named `azure-pipelines.yml` at your repository root. - -```yml title="azure-pipelines.yml" -trigger: - - main - -pool: - vmImage: ubuntu-latest - -steps: - - checkout: self - persistCredentials: true - - - task: NodeTool@0 - inputs: - versionSpec: '18' - displayName: Install Node.js - - - script: | - git config --global user.name "${GH_NAME}" - git config --global user.email "${GH_EMAIL}" - git checkout -b main - echo "machine github.com login ${GH_NAME} password ${GH_TOKEN}" > ~/.netrc - yarn install - GIT_USER="${GH_NAME}" yarn deploy - env: - GH_NAME: $(GH_NAME) - GH_EMAIL: $(GH_EMAIL) - GH_TOKEN: $(GH_TOKEN) - displayName: Install and build -``` - -### Using Drone {#using-drone} - -1. Create a new SSH key that will be the [deploy key](https://docs.github.com/en/free-pro-team@latest/developers/overview/managing-deploy-keys#deploy-keys) for your project. -2. Name your private and public keys to be specific and so that it does not overwrite your other [SSH keys](https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent). -3. Go to `https://github.com/USERNAME/REPO/settings/keys` and add a new deploy key by pasting in the public key you just generated. -4. Open your Drone.io dashboard and log in. The URL looks like `https://cloud.drone.io/USERNAME/REPO`. -5. Click on the repository, click on activate repository, and add a secret called `git_deploy_private_key` with your private key value that you just generated. -6. Create a `.drone.yml` on the root of your repository with the below text. - -```yml title=".drone.yml" -kind: pipeline -type: docker -trigger: - event: - - tag -- name: Website - image: node - commands: - - mkdir -p $HOME/.ssh - - ssh-keyscan -t rsa github.com >> $HOME/.ssh/known_hosts - - echo "$GITHUB_PRIVATE_KEY" > "$HOME/.ssh/id_rsa" - - chmod 0600 $HOME/.ssh/id_rsa - - cd website - - yarn install - - yarn deploy - environment: - USE_SSH: true - GITHUB_PRIVATE_KEY: - from_secret: git_deploy_private_key -``` - -Now, whenever you push a new tag to GitHub, this trigger will start the drone CI job to publish your website. - -## Deploying to Koyeb {#deploying-to-koyeb} - -[Koyeb](https://www.koyeb.com) is a developer-friendly serverless platform to deploy apps globally. The platform lets you seamlessly run Docker containers, web apps, and APIs with git-based deployment, native autoscaling, a global edge network, and built-in service mesh and discovery. Check out the [Koyeb's Docusaurus deployment guide](https://www.koyeb.com/tutorials/deploy-docusaurus-on-koyeb) to get started. - -## Deploying to Render {#deploying-to-render} - -[Render](https://render.com) offers [free static site hosting](https://render.com/docs/static-sites) with fully managed SSL, custom domains, a global CDN, and continuous auto-deploy from your Git repo. Get started in just a few minutes by following [Render's guide to deploying Docusaurus](https://render.com/docs/deploy-docusaurus). - -## Deploying to Qovery {#deploying-to-qovery} - -[Qovery](https://www.qovery.com) is a fully-managed cloud platform that runs on your AWS, Digital Ocean, and Scaleway account where you can host static sites, backend APIs, databases, cron jobs, and all your other apps in one place. - -1. Create a Qovery account. Visit the [Qovery dashboard](https://console.qovery.com) to create an account if you don't already have one. -2. Create a project. - - Click on **Create project** and give a name to your project. - - Click on **Next**. -3. Create a new environment. - - Click on **Create environment** and give a name (e.g. staging, production). -4. Add an application. - - Click on **Create an application**, give a name and select your GitHub or GitLab repository where your Docusaurus app is located. - - Define the main branch name and the root application path. - - Click on **Create**. After the application is created: - - Navigate to your application **Settings** - - Select **Port** - - Add port used by your Docusaurus application -5. Deploy All you have to do now is to navigate to your application and click on **Deploy**. - -![Deploy the app](https://hub.qovery.com/img/heroku/heroku-1.png) - -That's it. Watch the status and wait till the app is deployed. To open the application in your browser, click on **Action** and **Open** in your application overview. - -## Deploying to Hostman {#deploying-to-hostman} - -[Hostman](https://hostman.com/) allows you to host static websites for free. Hostman automates everything, you just need to connect your repository and follow easy steps: - -1. Create a service. - - To deploy a Docusaurus static website, click **Create** in the top-left corner of your [Dashboard](https://dashboard.hostman.com/) and choose **Front-end app or static website**. - -2. Select the project to deploy. - - If you are logged in to Hostman with your GitHub, GitLab, or Bitbucket account, at this point you will see the repository with your projects, including the private ones. - - Choose the project you want to deploy. It must contain the directory with the project's files (e.g. `website`). - - To access a different repository, click **Connect another repository**. - - If you didn't use your Git account credentials to log in, you'll be able to access the necessary account now, and then select the project. - -3. Configure the build settings. - - Next, the **Website customization** window will appear. Choose the **Static website** option from the list of frameworks. - - The **Directory with app** points at the directory that will contain the project's files after the build. You can leave it empty if during Step 2 you selected the repository with the contents of the website (or `my_website`) directory. - - The standard build command for Docusaurus will be: - - ```bash npm2yarn - npm run build - ``` - - You can modify the build command if needed. You can enter multiple commands separated by `&&`. - -4. Deploy. - - Click **Deploy** to start the build process. - - Once it starts, you will enter the deployment log. If there are any issues with the code, you will get warning or error messages in the log, specifying the cause of the problem. Usually, the log contains all the debugging data you'll need. - - When the deployment is complete, you will receive an email notification and also see a log entry. All done! Your project is up and ready. - -## Deploying to Surge {#deploying-to-surge} - -Surge is a [static web hosting platform](https://surge.sh/help/getting-started-with-surge), it is used to deploy your Docusaurus project from the command line in a minute. Deploying your project to Surge is easy and it is also free (including a custom domain and SSL). - -Deploy your app in a matter of seconds using surge with the following steps: - -1. First, install Surge using npm by running the following command: - ```bash npm2yarn - npm install -g surge - ``` -2. To build the static files of your site for production in the root directory of your project, run: - ```bash npm2yarn - npm run build - ``` -3. Then, run this command inside the root directory of your project: - ```bash - surge build/ - ``` - -First-time users of Surge would be prompted to create an account from the command line (which happens only once). - -Confirm that the site you want to publish is in the `build` directory, a randomly generated subdomain `*.surge.sh subdomain` is always given (which can be edited). - -### Using your domain {#using-your-domain} - -If you have a domain name you can deploy your site using surge to your domain using the command: - -```bash -surge build/ your-domain.com -``` - -Your site is now deployed for free at `subdomain.surge.sh` or `your-domain.com` depending on the method you chose. - -### Setting up CNAME file {#setting-up-cname-file} - -Store your domain in a CNAME file for future deployments with the following command: - -```bash -echo subdomain.surge.sh > CNAME -``` - -You can deploy any other changes in the future with the command `surge`. - -## Deploying to QuantCDN {#deploying-to-quantcdn} - -1. Install [Quant CLI](https://docs.quantcdn.io/docs/cli/get-started) -2. Create a QuantCDN account by [signing up](https://dashboard.quantcdn.io/register) -3. Initialize your project with `quant init` and fill in your credentials: - ```bash - quant init - ``` -4. Deploy your site. - ```bash - quant deploy - ``` - -See [docs](https://docs.quantcdn.io/docs/cli/continuous-integration) and [blog](https://www.quantcdn.io/blog) for more examples and use cases for deploying to QuantCDN. - -## Deploying to Layer0 {#deploying-to-layer0} - -[Layer0](https://www.layer0.co) is an all-in-one platform to develop, deploy, preview, experiment on, monitor, and run your headless frontend. It is focused on large, dynamic websites and best-in-class performance through EdgeJS (a JavaScript-based Content Delivery Network), predictive prefetching, and performance monitoring. Layer0 offers a free tier. Get started in just a few minutes by following [Layer0's guide to deploying Docusaurus](https://docs.layer0.co/guides/docusaurus). - -## Deploying to Cloudflare Pages {#deploying-to-cloudflare-pages} - -[Cloudflare Pages](https://pages.cloudflare.com/) is a Jamstack platform for frontend developers to collaborate and deploy websites. Get started within a few minutes by following [this article](https://dev.to/apidev234/deploying-docusaurus-to-cloudflare-pages-565g). - -## Deploying to Azure Static Web Apps {#deploying-to-azure-static-web-apps} - -[Azure Static Web Apps](https://docs.microsoft.com/en-us/azure/static-web-apps/overview) is a service that automatically builds and deploys full-stack web apps to Azure directly from the code repository, simplifying the developer experience for CI/CD. Static Web Apps separates the web application's static assets from its dynamic (API) endpoints. Static assets are served from globally-distributed content servers, making it faster for clients to retrieve files using servers nearby. Dynamic APIs are scaled with serverless architectures, using an event-driven functions-based approach that is more cost-effective and scales on demand. Get started in a few minutes by following [this step-by-step guide](https://dev.to/azure/11-share-content-with-docusaurus-azure-static-web-apps-30hc). diff --git a/website/versioned_docs/version-2.0.0-rc.1/docusaurus-core.md b/website/versioned_docs/version-2.0.0-rc.1/docusaurus-core.md deleted file mode 100644 index ee932f0eed6e..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/docusaurus-core.md +++ /dev/null @@ -1,727 +0,0 @@ ---- -sidebar_label: Client API ---- - -# Docusaurus Client API - -Docusaurus provides some APIs on the clients that can be helpful to you when building your site. - -## Components {#components} - -### `<ErrorBoundary />` {#errorboundary} - -This component creates a [React error boundary](https://reactjs.org/docs/error-boundaries.html). - -Use it to wrap components that might throw, and display a fallback when that happens instead of crashing the whole app. - -```jsx -import React from 'react'; -import ErrorBoundary from '@docusaurus/ErrorBoundary'; - -const SafeComponent = () => ( - <ErrorBoundary - fallback={({error, tryAgain}) => ( - <div> - <p>This component crashed because of error: {error.message}.</p> - <button onClick={tryAgain}>Try Again!</button> - </div> - )}> - <SomeDangerousComponentThatMayThrow /> - </ErrorBoundary> -); -``` - -```mdx-code-block -import ErrorBoundaryTestButton from "@site/src/components/ErrorBoundaryTestButton" -``` - -:::tip - -To see it in action, click here: <ErrorBoundaryTestButton/> - -::: - -:::info - -Docusaurus uses this component to catch errors within the theme's layout, and also within the entire app. - -::: - -:::note - -This component doesn't catch build-time errors and only protects against client-side render errors that can happen when using stateful React components. - -::: - -#### Props {#errorboundary-props} - -- `fallback`: an optional render callback returning a JSX element. It will receive an object with 2 attributes: `error`, the error that was caught, and `tryAgain`, a function (`() => void`) callback to reset the error in the component and try rendering it again. If not present, `@theme/Error` will be rendered instead. `@theme/Error` is used for the error boundaries wrapping the site, above the layout. - -:::caution - -The `fallback` prop is a callback, and **not a React functional component**. You can't use React hooks inside this callback. - -::: - -### `<Head/>` {#head} - -This reusable React component will manage all of your changes to the document head. It takes plain HTML tags and outputs plain HTML tags and is beginner-friendly. It is a wrapper around [React Helmet](https://github.com/nfl/react-helmet). - -Usage Example: - -```jsx -import React from 'react'; -// highlight-next-line -import Head from '@docusaurus/Head'; - -const MySEO = () => ( - // highlight-start - <Head> - <meta property="og:description" content="My custom description" /> - <meta charSet="utf-8" /> - <title>My Title - - - // highlight-end -); -``` - -Nested or latter components will override duplicate usages: - -```jsx - - {/* highlight-start */} - - My Title - - - {/* highlight-end */} - - {/* highlight-start */} - - Nested Title - - - {/* highlight-end */} - - -``` - -Outputs: - -```html - - Nested Title - - -``` - -### `` {#link} - -This component enables linking to internal pages as well as a powerful performance feature called preloading. Preloading is used to prefetch resources so that the resources are fetched by the time the user navigates with this component. We use an `IntersectionObserver` to fetch a low-priority request when the `` is in the viewport and then use an `onMouseOver` event to trigger a high-priority request when it is likely that a user will navigate to the requested resource. - -The component is a wrapper around react-router’s `` component that adds useful enhancements specific to Docusaurus. All props are passed through to react-router’s `` component. - -External links also work, and automatically have these props: `target="_blank" rel="noopener noreferrer"`. - -```jsx -import React from 'react'; -// highlight-next-line -import Link from '@docusaurus/Link'; - -const Page = () => ( -
-

- {/* highlight-next-line */} - Check out my blog! -

-

- {/* highlight-next-line */} - Follow me on Twitter! -

-
-); -``` - -#### `to`: string {#to-string} - -The target location to navigate to. Example: `/docs/introduction`. - -```jsx - -``` - -:::tip - -Prefer this component to vanilla `` tags because Docusaurus does a lot of optimizations (e.g. broken path detection, prefetching, applying base URL...) if you use ``. - -::: - -### `` {#redirect} - -Rendering a `` will navigate to a new location. The new location will override the current location in the history stack like server-side redirects (HTTP 3xx) do. You can refer to [React Router's Redirect documentation](https://reacttraining.com/react-router/web/api/Redirect) for more info on available props. - -Example usage: - -```jsx -import React from 'react'; -// highlight-next-line -import {Redirect} from '@docusaurus/router'; - -const Home = () => { - // highlight-next-line - return ; -}; -``` - -:::note - -`@docusaurus/router` implements [React Router](https://reacttraining.com/react-router/web/guides/quick-start) and supports its features. - -::: - -### `` {#browseronly} - -The `` component permits to render React components only in the browser after the React app has hydrated. - -:::tip - -Use it for integrating with code that can't run in Node.js, because the `window` or `document` objects are being accessed. - -::: - -#### Props {#browseronly-props} - -- `children`: render function prop returning browser-only JSX. Will not be executed in Node.js -- `fallback` (optional): JSX to render on the server (Node.js) and until React hydration completes. - -#### Example with code {#browseronly-example-code} - -```jsx -// highlight-start -import BrowserOnly from '@docusaurus/BrowserOnly'; -// highlight-end - -const MyComponent = () => { - return ( - // highlight-start - - {() => page url = {window.location.href}} - - // highlight-end - ); -}; -``` - -#### Example with a library {#browseronly-example-library} - -```jsx -// highlight-start -import BrowserOnly from '@docusaurus/BrowserOnly'; -// highlight-end - -const MyComponent = (props) => { - return ( - // highlight-start - Loading...}> - {() => { - const LibComponent = require('some-lib').LibComponent; - return ; - }} - - // highlight-end - ); -}; -``` - -### `` {#interpolate} - -A simple interpolation component for text containing dynamic placeholders. - -The placeholders will be replaced with the provided dynamic values and JSX elements of your choice (strings, links, styled elements...). - -#### Props {#interpolate-props} - -- `children`: text containing interpolation placeholders like `{placeholderName}` -- `values`: object containing interpolation placeholder values - -```jsx -import React from 'react'; -import Link from '@docusaurus/Link'; -import Interpolate from '@docusaurus/Interpolate'; - -export default function VisitMyWebsiteMessage() { - return ( - // highlight-start - - website - - ), - }}> - {'Hello, {firstName}! How are you? Take a look at my {website}'} - - // highlight-end - ); -} -``` - -### `` {#translate} - -When [localizing your site](./i18n/i18n-introduction.md), the `` component will allow providing **translation support to React components**, such as your homepage. The `` component supports [interpolation](#interpolate). - -The translation strings will statically extracted from your code with the [`docusaurus write-translations`](./cli.md#docusaurus-write-translations-sitedir) CLI and a `code.json` translation file will be created in `website/i18n/[locale]`. - -:::note - -The `` props **must be hardcoded strings**. - -Apart from the `values` prop used for interpolation, it is **not possible to use variables**, or the static extraction wouldn't work. - -::: - -#### Props {#translate-props} - -- `children`: untranslated string in the default site locale (can contain [interpolation placeholders](#interpolate)) -- `id`: optional value to be used as the key in JSON translation files -- `description`: optional text to help the translator -- `values`: optional object containing interpolation placeholder values - -#### Example {#example} - -```jsx title="src/pages/index.js" -import React from 'react'; -import Layout from '@theme/Layout'; - -// highlight-start -import Translate from '@docusaurus/Translate'; -// highlight-end - -export default function Home() { - return ( - -

- {/* highlight-start */} - - Welcome to my website - - {/* highlight-end */} -

-
- {/* highlight-start */} - - {'Welcome, {firstName}! How are you?'} - - {/* highlight-end */} -
-
- ); -} -``` - -:::note - -You can even omit the children prop and specify a translation string in your `code.json` file manually after running the `docusaurus write-translations` CLI command. - -```jsx - -``` - -::: - -## Hooks {#hooks} - -### `useDocusaurusContext` {#useDocusaurusContext} - -React hook to access Docusaurus Context. The context contains the `siteConfig` object from [docusaurus.config.js](api/docusaurus.config.js.md) and some additional site metadata. - -```ts -type PluginVersionInformation = - | {readonly type: 'package'; readonly version?: string} - | {readonly type: 'project'} - | {readonly type: 'local'} - | {readonly type: 'synthetic'}; - -type SiteMetadata = { - readonly docusaurusVersion: string; - readonly siteVersion?: string; - readonly pluginVersions: Record; -}; - -type I18nLocaleConfig = { - label: string; - direction: string; -}; - -type I18n = { - defaultLocale: string; - locales: [string, ...string[]]; - currentLocale: string; - localeConfigs: Record; -}; - -type DocusaurusContext = { - siteConfig: DocusaurusConfig; - siteMetadata: SiteMetadata; - globalData: Record; - i18n: I18n; - codeTranslations: Record; -}; -``` - -Usage example: - -```jsx -import React from 'react'; -import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; - -const MyComponent = () => { - // highlight-next-line - const {siteConfig, siteMetadata} = useDocusaurusContext(); - return ( -
- {/* highlight-start */} -

{siteConfig.title}

-
{siteMetadata.siteVersion}
-
{siteMetadata.docusaurusVersion}
- {/* highlight-end */} -
- ); -}; -``` - -:::note - -The `siteConfig` object only contains **serializable values** (values that are preserved after `JSON.stringify()`). Functions, regexes, etc. would be lost on the client side. - -::: - -### `useIsBrowser` {#useIsBrowser} - -Returns `true` when the React app has successfully hydrated in the browser. - -:::caution - -Use this hook instead of `typeof windows !== 'undefined'` in React rendering logic. - -The first client-side render output (in the browser) **must be exactly the same** as the server-side render output (Node.js). Not following this rule can lead to unexpected hydration behaviors, as described in [The Perils of Rehydration](https://www.joshwcomeau.com/react/the-perils-of-rehydration/). - -::: - -Usage example: - -```jsx -import React from 'react'; -import useIsBrowser from '@docusaurus/useIsBrowser'; - -const MyComponent = () => { - // highlight-start - const isBrowser = useIsBrowser(); - // highlight-end - return
{isBrowser ? 'Client' : 'Server'}
; -}; -``` - -### `useBaseUrl` {#useBaseUrl} - -React hook to prepend your site `baseUrl` to a string. - -:::caution - -**Don't use it for regular links!** - -The `/baseUrl/` prefix is automatically added to all **absolute paths** by default: - -- Markdown: `[link](/my/path)` will link to `/baseUrl/my/path` -- React: `link` will link to `/baseUrl/my/path` - -::: - -#### Options {#options} - -```ts -type BaseUrlOptions = { - forcePrependBaseUrl: boolean; - absolute: boolean; -}; -``` - -#### Example usage: {#example-usage} - -```jsx -import React from 'react'; -import useBaseUrl from '@docusaurus/useBaseUrl'; - -const SomeImage = () => { - // highlight-start - const imgSrc = useBaseUrl('/img/myImage.png'); - // highlight-end - return ; -}; -``` - -:::tip - -In most cases, you don't need `useBaseUrl`. - -Prefer a `require()` call for [assets](./guides/markdown-features/markdown-features-assets.mdx): - -```jsx - -``` - -::: - -### `useBaseUrlUtils` {#useBaseUrlUtils} - -Sometimes `useBaseUrl` is not good enough. This hook return additional utils related to your site's base URL. - -- `withBaseUrl`: useful if you need to add base URLs to multiple URLs at once. - -```jsx -import React from 'react'; -import {useBaseUrlUtils} from '@docusaurus/useBaseUrl'; - -const Component = () => { - const urls = ['/a', '/b']; - // highlight-start - const {withBaseUrl} = useBaseUrlUtils(); - const urlsWithBaseUrl = urls.map(withBaseUrl); - // highlight-end - return
{/* ... */}
; -}; -``` - -### `useGlobalData` {#useGlobalData} - -React hook to access Docusaurus global data created by all the plugins. - -Global data is namespaced by plugin name then by plugin ID. - -:::info - -Plugin ID is only useful when a plugin is used multiple times on the same site. Each plugin instance is able to create its own global data. - -::: - -```ts -type GlobalData = Record< - PluginName, - Record< - PluginId, // "default" by default - any // plugin-specific data - > ->; -``` - -Usage example: - -```jsx -import React from 'react'; -// highlight-next-line -import useGlobalData from '@docusaurus/useGlobalData'; - -const MyComponent = () => { - // highlight-start - const globalData = useGlobalData(); - const myPluginData = globalData['my-plugin']['default']; - return
{myPluginData.someAttribute}
; - // highlight-end -}; -``` - -:::tip - -Inspect your site's global data at `./docusaurus/globalData.json` - -::: - -### `usePluginData` {#usePluginData} - -Access global data created by a specific plugin instance. - -This is the most convenient hook to access plugin global data and should be used most of the time. - -`pluginId` is optional if you don't use multi-instance plugins. - -```ts -function usePluginData( - pluginName: string, - pluginId?: string, - options?: {failfast?: boolean}, -); -``` - -Usage example: - -```jsx -import React from 'react'; -// highlight-next-line -import {usePluginData} from '@docusaurus/useGlobalData'; - -const MyComponent = () => { - // highlight-start - const myPluginData = usePluginData('my-plugin'); - return
{myPluginData.someAttribute}
; - // highlight-end -}; -``` - -### `useAllPluginInstancesData` {#useAllPluginInstancesData} - -Access global data created by a specific plugin. Given a plugin name, it returns the data of all the plugins instances of that name, by plugin id. - -```ts -function useAllPluginInstancesData( - pluginName: string, - options?: {failfast?: boolean}, -); -``` - -Usage example: - -```jsx -import React from 'react'; -// highlight-next-line -import {useAllPluginInstancesData} from '@docusaurus/useGlobalData'; - -const MyComponent = () => { - // highlight-start - const allPluginInstancesData = useAllPluginInstancesData('my-plugin'); - const myPluginData = allPluginInstancesData['default']; - return
{myPluginData.someAttribute}
; - // highlight-end -}; -``` - -## Functions {#functions} - -### `interpolate` {#interpolate-1} - -The imperative counterpart of the [``](#interpolate) component. - -#### Signature {#signature} - -```ts -// Simple string interpolation -function interpolate(text: string, values: Record): string; - -// JSX interpolation -function interpolate( - text: string, - values: Record, -): ReactNode; -``` - -#### Example {#example-1} - -```js -// highlight-next-line -import {interpolate} from '@docusaurus/Interpolate'; - -const message = interpolate('Welcome {firstName}', {firstName: 'Sébastien'}); -``` - -### `translate` {#translate-imperative} - -The imperative counterpart of the [``](#translate) component. Also supporting [placeholders interpolation](#interpolate). - -:::tip - -Use the imperative API for the **rare cases** where a **component cannot be used**, such as: - -- the page `title` metadata -- the `placeholder` props of form inputs -- the `aria-label` props for accessibility - -::: - -#### Signature {#signature-1} - -```ts -function translate( - translation: {message: string; id?: string; description?: string}, - values: Record, -): string; -``` - -#### Example {#example-2} - -```jsx title="src/pages/index.js" -import React from 'react'; -import Layout from '@theme/Layout'; - -// highlight-next-line -import {translate} from '@docusaurus/Translate'; - -export default function Home() { - return ( - - - - ); -} -``` - -## Modules {#modules} - -### `ExecutionEnvironment` {#executionenvironment} - -A module that exposes a few boolean variables to check the current rendering environment. - -:::caution - -For React rendering logic, use [`useIsBrowser()`](#useIsBrowser) or [``](#browseronly) instead. - -::: - -Example: - -```js -import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; - -if (ExecutionEnvironment.canUseDOM) { - require('lib-that-only-works-client-side'); -} -``` - -| Field | Description | -| --- | --- | -| `ExecutionEnvironment.canUseDOM` | `true` if on client/browser, `false` on Node.js/prerendering. | -| `ExecutionEnvironment.canUseEventListeners` | `true` if on client and has `window.addEventListener`. | -| `ExecutionEnvironment.canUseIntersectionObserver` | `true` if on client and has `IntersectionObserver`. | -| `ExecutionEnvironment.canUseViewport` | `true` if on client and has `window.screen`. | - -### `constants` {#constants} - -A module exposing useful constants to client-side theme code. - -```js -import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants'; -``` - -| Named export | Value | -| ------------------- | --------- | -| `DEFAULT_PLUGIN_ID` | `default` | diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/creating-pages.md b/website/versioned_docs/version-2.0.0-rc.1/guides/creating-pages.md deleted file mode 100644 index fbc89e20d6ce..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/creating-pages.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -slug: /creating-pages -sidebar_label: Pages ---- - -# Creating Pages - -In this section, we will learn about creating pages in Docusaurus. - -The `@docusaurus/plugin-content-pages` plugin empowers you to create **one-off standalone pages** like a showcase page, playground page, or support page. You can use React components, or Markdown. - -:::note - -Pages do not have sidebars, only [docs](./docs/docs-introduction.md) do. - -::: - -:::info - -Check the [Pages Plugin API Reference documentation](./../api/plugins/plugin-content-pages.md) for an exhaustive list of options. - -::: - -## Add a React page {#add-a-react-page} - -React is used as the UI library to create pages. Every page component should export a React component, and you can leverage the expressiveness of React to build rich and interactive content. - -Create a file `/src/pages/helloReact.js`: - -```jsx title="/src/pages/helloReact.js" -import React from 'react'; -import Layout from '@theme/Layout'; - -export default function Hello() { - return ( - -
-

- Edit pages/helloReact.js and save to reload. -

-
-
- ); -} -``` - -Once you save the file, the development server will automatically reload the changes. Now open [http://localhost:3000/helloReact](http://localhost:3000/helloReact) and you will see the new page you just created. - -Each page doesn't come with any styling. You will need to import the `Layout` component from `@theme/Layout` and wrap your contents within that component if you want the navbar and/or footer to appear. - -:::tip - -You can also create TypeScript pages with the `.tsx` extension (`helloReact.tsx`). - -::: - -## Add a Markdown page {#add-a-markdown-page} - -Create a file `/src/pages/helloMarkdown.md`: - -```md title="/src/pages/helloMarkdown.md" ---- -title: my hello page title -description: my hello page description -hide_table_of_contents: true ---- - -# Hello - -How are you? -``` - -In the same way, a page will be created at [http://localhost:3000/helloMarkdown](http://localhost:3000/helloMarkdown). - -Markdown pages are less flexible than React pages because it always uses the theme layout. - -Here's an [example Markdown page](/examples/markdownPageExample). - -:::tip - -You can use the full power of React in Markdown pages too, refer to the [MDX](https://mdxjs.com/) documentation. - -::: - -## Routing {#routing} - -If you are familiar with other static site generators like Jekyll and Next, this routing approach will feel familiar to you. Any JavaScript file you create under `/src/pages/` directory will be automatically converted to a website page, following the `/src/pages/` directory hierarchy. For example: - -- `/src/pages/index.js` → `[baseUrl]` -- `/src/pages/foo.js` → `[baseUrl]/foo` -- `/src/pages/foo/test.js` → `[baseUrl]/foo/test` -- `/src/pages/foo/index.js` → `[baseUrl]/foo/` - -In this component-based development era, it is encouraged to co-locate your styling, markup, and behavior together into components. Each page is a component, and if you need to customize your page design with your own styles, we recommend co-locating your styles with the page component in its own directory. For example, to create a "Support" page, you could do one of the following: - -- Add a `/src/pages/support.js` file -- Create a `/src/pages/support/` directory and a `/src/pages/support/index.js` file. - -The latter is preferred as it has the benefits of letting you put files related to the page within that directory. For example, a CSS module file (`styles.module.css`) with styles meant to only be used on the "Support" page. - -:::note - -This is merely a recommended directory structure, and you will still need to manually import the CSS module file within your component module (`support/index.js`). - -::: - -By default, any Markdown or JavaScript file starting with `_` will be ignored and no routes will be created for that file (see the `exclude` option). - -```bash -my-website -├── src -│ └── pages -│ ├── styles.module.css -│ ├── index.js -│ ├── _ignored.js -│ ├── _ignored-folder -│ │ ├── Component1.js -│ │ └── Component2.js -│ └── support -│ ├── index.js -│ └── styles.module.css -. -``` - -:::caution - -All JavaScript/TypeScript files within the `src/pages/` directory will have corresponding website paths generated for them. If you want to create reusable components into that directory, use the `exclude` option (by default, files prefixed with `_`, test files(`.test.js`), and files in `__tests__` directory are not turned into pages). - -::: - -### Duplicate Routes {#duplicate-routes} - -You may accidentally create multiple pages that are meant to be accessed on the same route. When this happens, Docusaurus will warn you about duplicate routes when you run `yarn start` or `yarn build`, but the site will still be built successfully. The page that was created last will be accessible, but it will override other conflicting pages. To resolve this issue, you should modify or remove any conflicting routes. diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/docs-create-doc.mdx b/website/versioned_docs/version-2.0.0-rc.1/guides/docs/docs-create-doc.mdx deleted file mode 100644 index 5221a2a0e37d..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/docs-create-doc.mdx +++ /dev/null @@ -1,166 +0,0 @@ ---- -id: create-doc -description: Create a Markdown Document -slug: /create-doc ---- - -# Create a doc - -Create a Markdown file, `greeting.md`, and place it under the `docs` directory. - -```bash -website # root directory of your site -├── docs -│ └── greeting.md -├── src -│ └── pages -├── docusaurus.config.js -├── ... -``` - -```md ---- -description: Create a doc page with rich content. ---- - -# Hello from Docusaurus - -Are you ready to create the documentation site for your open source project? - -## Headers - -will show up on the table of contents on the upper right - -So that your users will know what this page is all about without scrolling down or even without reading too much. - -## Only h2 and h3 will be in the TOC by default. - -You can configure the TOC heading levels either per-document or in the theme configuration. - -The headers are well-spaced so that the hierarchy is clear. - -- lists will help you -- present the key points -- that you want your users to remember - - and you may nest them - - multiple times - -## Custom ID headers {#custom-id} - -With `{#custom-id}` syntax you can set your own header ID. -``` - -:::note - -All files prefixed with an underscore (`_`) under the `docs` directory are treated as "partial" pages and will be ignored by default. - -Read more about [importing partial pages](../markdown-features/markdown-features-react.mdx#importing-markdown). - -::: - -## Doc front matter {#doc-front-matter} - -The [front matter](../markdown-features/markdown-features-intro.mdx#front-matter) is used to provide additional metadata for your doc page. Front matter is optional—Docusaurus will be able to infer all necessary metadata without the front matter. For example, the [doc tags](#dog-tags) feature introduced below requires using front matter. For all possible fields, see [the API documentation](../../api/plugins/plugin-content-docs.md#markdown-front-matter). - -## Doc tags {#doc-tags} - -Optionally, you can add tags to your doc pages, which introduces another dimension of categorization in addition to the [docs sidebar](./sidebar/index.md). Tags are passed in the front matter as a list of labels: - -```md "your-doc-page.md" ---- -id: doc-with-tags -title: A doc with tags -tags: - - Demo - - Getting started ---- -``` - -:::tip - -Tags can also be declared with `tags: [Demo, Getting started]`. - -Read more about all the possible [Yaml array syntaxes](https://www.w3schools.io/file/yaml-arrays/). - -::: - -## Organizing folder structure {#organizing-folder-structure} - -How the Markdown files are arranged under the `docs` folder can have multiple impacts on Docusaurus content generation. However, most of them can be decoupled from the file structure. - -### Document ID {#document-id} - -Every document has a unique `id`. By default, a document `id` is the name of the document (without the extension) relative to the root docs directory. - -For example, the ID of `greeting.md` is `greeting`, and the ID of `guide/hello.md` is `guide/hello`. - -```bash -website # Root directory of your site -└── docs - ├── greeting.md - └── guide - └── hello.md -``` - -However, the **last part** of the `id` can be defined by the user in the front matter. For example, if `guide/hello.md`'s content is defined as below, its final `id` is `guide/part1`. - -```md ---- -id: part1 ---- - -Lorem ipsum -``` - -The ID is used to refer to a document when hand-writing sidebars, or when using docs-related layout components or hooks. - -### Doc URLs {#doc-urls} - -By default, a document's URL location is its file path relative to the `docs` folder. Use the `slug` front matter to change a document's URL. - -For example, suppose your site structure looks like this: - -```bash -website # Root directory of your site -└── docs - └── guide - └── hello.md -``` - -By default `hello.md` will be available at `/docs/guide/hello`. You can change its URL location to `/docs/bonjour`: - -```md ---- -slug: /bonjour ---- - -Lorem ipsum -``` - -`slug` will be appended to the doc plugin's `routeBasePath`, which is `/docs` by default. See [Docs-only mode](#docs-only-mode) for how to remove the `/docs` part from the URL. - -:::note - -It is possible to use: - -- absolute slugs: `slug: /mySlug`, `slug: /`... -- relative slugs: `slug: mySlug`, `slug: ./../mySlug`... - -::: - -If you want a document to be available at the root, and have a path like `https://docusaurus.io/docs/`, you can use the slug front matter: - -```md ---- -id: my-home-doc -slug: / ---- - -Lorem ipsum -``` - -### Sidebars {#sidebars} - -When using [autogenerated sidebars](./sidebar/autogenerated.md), the file structure will determine the sidebar structure. - -Our recommendation for file system organization is: make your file system mirror the sidebar structure (so you don't need to handwrite your `sidebars.js` file), and use the `slug` front matter to customize URLs of each document. diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/docs-introduction.md b/website/versioned_docs/version-2.0.0-rc.1/guides/docs/docs-introduction.md deleted file mode 100644 index 7aa09d0dd05b..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/docs-introduction.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -id: introduction -sidebar_label: Introduction -slug: /docs-introduction ---- - -# Docs Introduction - -The docs feature provides users with a way to organize Markdown files in a hierarchical format. - -:::info - -Check the [Docs Plugin API Reference documentation](./../../api/plugins/plugin-content-docs.md) for an exhaustive list of options. - -::: - -Your site's documentation is organized by four levels, from lowest to highest: - -1. Individual pages. -2. Sidebars. -3. Versions. -4. Plugin instances. - -The guide will introduce them in that order: starting from [how individual pages can be configured](./docs-create-doc.mdx), to [how to create a sidebar or multiple ones](./sidebar/index.md), to [how to create and manage versions](./versioning.md), to [how to use multiple docs plugin instances](./docs-multi-instance.mdx). - -## Docs-only mode {#docs-only-mode} - -A freshly initialized Docusaurus site has the following structure: - -``` -example.com/ -> generated from `src/pages/index.js` - -example.com/docs/intro -> generated from `docs/intro.md` -example.com/docs/tutorial-basics/... -> generated from `docs/tutorial-basics/...` -... - -example.com/blog/2021/08/26/welcome -> generated from `blog/2021-08-26-welcome/index.md` -example.com/blog/2021/08/01/mdx-blog-post -> generated from `blog/2021-08-01-mdx-blog-post.mdx` -... -``` - -All docs will be served under the subroute `docs/`. But what if **your site only has docs**, or you want to prioritize your docs by putting them at the root? - -Assume that you have the following in your configuration: - -```js title="docusaurus.config.js" -module.exports = { - // ... - presets: [ - '@docusaurus/preset-classic', - { - docs: { - /* docs plugin options */ - }, - blog: { - /* blog plugin options */ - }, - // ... - }, - ], -}; -``` - -To enter docs-only mode, change it to like this: - -```js title="docusaurus.config.js" -module.exports = { - // ... - presets: [ - '@docusaurus/preset-classic', - { - docs: { - // highlight-next-line - routeBasePath: '/', // Serve the docs at the site's root - /* other docs plugin options */ - }, - // highlight-next-line - blog: false, // Optional: disable the blog plugin - // ... - }, - ], -}; -``` - -Note that you **don't necessarily have to give up on using the blog** or other plugins; all that `routeBasePath: '/'` does is that instead of serving the docs through `https://example.com/docs/some-doc`, they are now at the site root: `https://example.com/some-doc`. The blog, if enabled, can still be accessed through the `blog/` subroute. - -Don't forget to put some page at the root (`https://example.com/`) through adding the front matter: - -```md title="docs/intro.md" ---- -# highlight-next-line -slug: / ---- - -This page will be the home page when users visit https://example.com/. -``` - -:::caution - -If you added `slug: /` to a doc to make it the homepage, you should delete the existing homepage at `./src/pages/index.js`, or else there will be two files mapping to the same route! - -::: - -Now, the site's structure will be like the following: - -``` -example.com/ -> generated from `docs/intro.md` -example.com/tutorial-basics/... -> generated from `docs/tutorial-basics/...` -... -``` - -:::tip - -There's also a "blog-only mode" for those who only want to use the blog feature of Docusaurus 2. You can use the same method detailed above. Follow the setup instructions on [Blog-only mode](../../blog.mdx#blog-only-mode). - -::: diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/docs-multi-instance.mdx b/website/versioned_docs/version-2.0.0-rc.1/guides/docs/docs-multi-instance.mdx deleted file mode 100644 index 69a1a1656ce2..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/docs-multi-instance.mdx +++ /dev/null @@ -1,213 +0,0 @@ ---- -id: multi-instance -description: Use multiple docs plugin instances on a single Docusaurus site. -slug: /docs-multi-instance ---- - -# Docs Multi-instance - -The `@docusaurus/plugin-content-docs` plugin can support [multi-instance](../../using-plugins.md#multi-instance-plugins-and-plugin-ids). - -:::note - -This feature is only useful for [versioned documentation](./versioning.md). It is recommended to be familiar with docs versioning before reading this page. If you just want [multiple sidebars](./sidebar/multiple-sidebars.md), you can do so within one plugin. - -::: - -## Use-cases {#use-cases} - -Sometimes you want a Docusaurus site to host 2 distinct sets of documentation (or more). - -These documentations may even have different versioning/release lifecycles. - -### Mobile SDKs documentation {#mobile-sdks-documentation} - -If you build a cross-platform mobile SDK, you may have 2 documentations: - -- Android SDK documentation (`v1.0`, `v1.1`) -- iOS SDK documentation (`v1.0`, `v2.0`) - -In this case, you can use a distinct docs plugin instance per mobile SDK documentation. - -:::caution - -If each documentation instance is very large, you should rather create 2 distinct Docusaurus sites. - -If someone edits the iOS documentation, is it really useful to rebuild everything, including the whole Android documentation that did not change? - -::: - -### Versioned and unversioned doc {#versioned-and-unversioned-doc} - -Sometimes, you want some documents to be versioned, while other documents are more "global", and it feels useless to version them. - -We use this pattern on the Docusaurus website itself: - -- The [/docs/\*](/docs) section is versioned -- The [/community/\*](/community/support) section is unversioned - -## Setup {#setup} - -Suppose you have 2 documentations: - -- Product: some versioned doc about your product -- Community: some unversioned doc about the community around your product - -In this case, you should use the same plugin twice in your site configuration. - -:::caution - -`@docusaurus/preset-classic` already includes a docs plugin instance for you! - -::: - -When using the preset: - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - docs: { - // highlight-start - // id: 'product', // omitted => default instance - // highlight-end - path: 'product', - routeBasePath: 'product', - sidebarPath: require.resolve('./sidebarsProduct.js'), - // ... other options - }, - }, - ], - ], - plugins: [ - [ - '@docusaurus/plugin-content-docs', - { - // highlight-start - id: 'community', - // highlight-end - path: 'community', - routeBasePath: 'community', - sidebarPath: require.resolve('./sidebarsCommunity.js'), - // ... other options - }, - ], - ], -}; -``` - -When not using the preset: - -```js title="docusaurus.config.js" -module.exports = { - plugins: [ - [ - '@docusaurus/plugin-content-docs', - { - // highlight-start - // id: 'product', // omitted => default instance - // highlight-end - path: 'product', - routeBasePath: 'product', - sidebarPath: require.resolve('./sidebarsProduct.js'), - // ... other options - }, - ], - [ - '@docusaurus/plugin-content-docs', - { - // highlight-start - id: 'community', - // highlight-end - path: 'community', - routeBasePath: 'community', - sidebarPath: require.resolve('./sidebarsCommunity.js'), - // ... other options - }, - ], - ], -}; -``` - -Don't forget to assign a unique `id` attribute to plugin instances. - -:::note - -We consider that the `product` instance is the most important one, and make it the "default" instance by not assigning any ID. - -::: - -## Versioned paths {#versioned-paths} - -Each plugin instance will store versioned docs in a distinct folder. - -The default plugin instance will use these paths: - -- `website/versions.json` -- `website/versioned_docs` -- `website/versioned_sidebars` - -The other plugin instances (with an `id` attribute) will use these paths: - -- `website/[pluginId]_versions.json` -- `website/[pluginId]_versioned_docs` -- `website/[pluginId]_versioned_sidebars` - -:::tip - -You can omit the `id` attribute (defaults to `default`) for one of the docs plugin instances. - -The instance paths will be simpler, and retro-compatible with a single-instance setup. - -::: - -## Tagging new versions {#tagging-new-versions} - -Each plugin instance will have its own CLI command to tag a new version. They will be displayed if you run: - -```bash npm2yarn -npm run docusaurus -- --help -``` - -To version the product/default docs plugin instance: - -```bash npm2yarn -npm run docusaurus docs:version 1.0.0 -``` - -To version the non-default/community docs plugin instance: - -```bash npm2yarn -npm run docusaurus docs:version:community 1.0.0 -``` - -## Docs navbar items {#docs-navbar-items} - -Each docs-related [theme navbar items](../../api/themes/theme-configuration.md#navbar) take an optional `docsPluginId` attribute. - -For example, if you want to have one version dropdown for each mobile SDK (iOS and Android), you could do: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - navbar: { - items: [ - { - type: 'docsVersionDropdown', - // highlight-start - docsPluginId: 'ios', - // highlight-end - }, - { - type: 'docsVersionDropdown', - // highlight-start - docsPluginId: 'android', - // highlight-end - }, - ], - }, - }, -}; -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/autogenerated.md b/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/autogenerated.md deleted file mode 100644 index 88361f969dcc..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/autogenerated.md +++ /dev/null @@ -1,496 +0,0 @@ ---- -slug: /sidebar/autogenerated ---- - -# Autogenerated - -```mdx-code-block -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -``` - -Docusaurus can **create a sidebar automatically** from your **filesystem structure**: each folder creates a sidebar category, and each file creates a doc link. - -```ts -type SidebarItemAutogenerated = { - type: 'autogenerated'; - dirName: string; // Source folder to generate the sidebar slice from (relative to docs) -}; -``` - -Docusaurus can generate a full sidebar from your docs folder: - -```js title="sidebars.js" -module.exports = { - myAutogeneratedSidebar: [ - // highlight-start - { - type: 'autogenerated', - dirName: '.', // '.' means the current docs folder - }, - // highlight-end - ], -}; -``` - -An `autogenerated` item is converted by Docusaurus to a **sidebar slice** (also discussed in [category shorthands](items.md#category-shorthand)): a list of items of type `doc` or `category`, so you can splice **multiple `autogenerated` items** from multiple directories, interleaving them with regular sidebar items, in one sidebar level. - -
-A real-world example -Consider this file structure: - -```bash -docs -├── api -│ ├── product1-api -│ │ └── api.md -│ └── product2-api -│ ├── basic-api.md -│ └── pro-api.md -├── intro.md -└── tutorials - ├── advanced - │ ├── advanced1.md - │ ├── advanced2.md - │ └── read-more - │ ├── resource1.md - │ └── resource2.md - ├── easy - │ ├── easy1.md - │ └── easy2.md - ├── tutorial-end.md - ├── tutorial-intro.md - └── tutorial-medium.md -``` - -And assume every doc's ID is just its file name. If you define an autogenerated sidebar like this: - -```js title="sidebars.js" -module.exports = { - mySidebar: [ - 'intro', - { - type: 'category', - label: 'Tutorials', - items: [ - 'tutorial-intro', - // highlight-start - { - type: 'autogenerated', - dirName: 'tutorials/easy', // Generate sidebar slice from docs/tutorials/easy - }, - // highlight-end - 'tutorial-medium', - // highlight-start - { - type: 'autogenerated', - dirName: 'tutorials/advanced', // Generate sidebar slice from docs/tutorials/hard - }, - // highlight-end - 'tutorial-end', - ], - }, - // highlight-start - { - type: 'autogenerated', - dirName: 'api', // Generate sidebar slice from docs/api - }, - // highlight-end - { - type: 'category', - label: 'Community', - items: ['team', 'chat'], - }, - ], -}; -``` - -It would be resolved as: - -```js title="sidebars.js" -module.exports = { - mySidebar: [ - 'intro', - { - type: 'category', - label: 'Tutorials', - items: [ - 'tutorial-intro', - // highlight-start - // Two files in docs/tutorials/easy - 'easy1', - 'easy2', - // highlight-end - 'tutorial-medium', - // highlight-start - // Two files and a folder in docs/tutorials/hard - 'advanced1', - 'advanced2', - { - type: 'category', - label: 'read-more', - items: ['resource1', 'resource2'], - }, - // highlight-end - 'tutorial-end', - ], - }, - // highlight-start - // Two folders in docs/api - { - type: 'category', - label: 'product1-api', - items: ['api'], - }, - { - type: 'category', - label: 'product2-api', - items: ['basic-api', 'pro-api'], - }, - // highlight-end - { - type: 'category', - label: 'Community', - items: ['team', 'chat'], - }, - ], -}; -``` - -Note how the autogenerate source directories themselves don't become categories: only the items they contain do. This is what we mean by "sidebar slice". - -
- -## Category index convention {#category-index-convention} - -Docusaurus can automatically link a category to its index document. - -A category index document is a document following one of those filename conventions: - -- Named as `index` (case-insensitive): `docs/Guides/index.md` -- Named as `README` (case-insensitive): `docs/Guides/README.mdx` -- Same name as parent folder: `docs/Guides/Guides.md` - -This is equivalent to using a category with a [doc link](items.md#category-doc-link): - -```js title="sidebars.js" -module.exports = { - docs: [ - // highlight-start - { - type: 'category', - label: 'Guides', - link: {type: 'doc', id: 'Guides/index'}, - items: [], - }, - // highlight-end - ], -}; -``` - -:::tip - -Naming your introductory document `README.md` makes it show up when browsing the folder using the GitHub interface, while using `index.md` makes the behavior more in line with how HTML files are served. - -::: - -:::tip - -If a folder only has one index page, it will be turned into a link instead of a category. This is useful for **asset collocation**: - -``` -some-doc -├── index.md -├── img1.png -└── img2.png -``` - -::: - -
- -Customizing category index matching - -It is possible to opt out any of the category index conventions, or define even more conventions. You can inject your own `isCategoryIndex` matcher through the [`sidebarItemsGenerator`](#customize-the-sidebar-items-generator) callback. For example, you can also pick `intro` as another file name eligible for automatically becoming the category index. - -```js title="docusaurus.config.js" -module.exports = { - plugins: [ - [ - '@docusaurus/plugin-content-docs', - { - async sidebarItemsGenerator({ - ...args, - isCategoryIndex: defaultCategoryIndexMatcher, // The default matcher implementation, given below - defaultSidebarItemsGenerator, - }) { - return defaultSidebarItemsGenerator({ - ...args, - // highlight-start - isCategoryIndex(doc) { - return ( - // Also pick intro.md in addition to the default ones - doc.fileName.toLowerCase() === 'intro' || - defaultCategoryIndexMatcher(doc) - ); - }, - // highlight-end - }); - }, - }, - ], - ], -}; -``` - -Or choose to not have any category index convention. - -```js title="docusaurus.config.js" -module.exports = { - plugins: [ - [ - '@docusaurus/plugin-content-docs', - { - async sidebarItemsGenerator({ - ...args, - isCategoryIndex: defaultCategoryIndexMatcher, // The default matcher implementation, given below - defaultSidebarItemsGenerator, - }) { - return defaultSidebarItemsGenerator({ - ...args, - // highlight-start - isCategoryIndex() { - // No doc will be automatically picked as category index - return false; - }, - // highlight-end - }); - }, - }, - ], - ], -}; -``` - -The `isCategoryIndex` matcher will be provided with three fields: - -- `fileName`, the file's name without extension and with casing preserved -- `directories`, the list of directory names _from the lowest level to the highest level_, relative to the docs root directory -- `extension`, the file's extension, with a leading dot. - -For example, for a doc file at `guides/sidebar/autogenerated.md`, the props the matcher receives are - -```js -const props = { - fileName: 'autogenerated', - directories: ['sidebar', 'guides'], - extension: '.md', -}; -``` - -The default implementation is: - -```js -function isCategoryIndex({fileName, directories}) { - const eligibleDocIndexNames = [ - 'index', - 'readme', - directories[0].toLowerCase(), - ]; - return eligibleDocIndexNames.includes(fileName.toLowerCase()); -} -``` - -
- -## Autogenerated sidebar metadata {#autogenerated-sidebar-metadata} - -For handwritten sidebar definitions, you would provide metadata to sidebar items through `sidebars.js`; for autogenerated, Docusaurus would read them from the item's respective file. In addition, you may want to adjust the relative position of each item because, by default, items within a sidebar slice will be generated in **alphabetical order** (using file and folder names). - -### Doc item metadata {#doc-item-metadata} - -The `label`, `className`, and `customProps` attributes are declared in front matter as `sidebar_label`, `sidebar_class_name`, and `sidebar_custom_props`, respectively. Position can be specified in the same way, via `sidebar_position` front matter. - -```md title="docs/tutorials/tutorial-easy.md" ---- -# highlight-start -sidebar_position: 2 -sidebar_label: Easy -sidebar_class_name: green -# highlight-end ---- - -# Easy Tutorial - -This is the easy tutorial! -``` - -### Category item metadata {#category-item-metadata} - -Add a `_category_.json` or `_category_.yml` file in the respective folder. You can specify any category metadata and also the `position` metadata. `label`, `className`, `position`, and `customProps` will default to the respective values of the category's linked doc, if there is one. - - - - -```json title="docs/tutorials/_category_.json" -{ - "position": 2.5, - "label": "Tutorial", - "collapsible": true, - "collapsed": false, - "className": "red", - "link": { - "type": "generated-index", - "title": "Tutorial overview" - }, - "customProps": { - "description": "This description can be used in the swizzled DocCard" - } -} -``` - - - - -```yml title="docs/tutorials/_category_.yml" -position: 2.5 # float position is supported -label: 'Tutorial' -collapsible: true # make the category collapsible -collapsed: false # keep the category open by default -className: red -link: - type: generated-index - title: Tutorial overview -customProps: - description: This description can be used in the swizzled DocCard -``` - - - - -:::info - -If the `link` is explicitly specified, Docusaurus will not apply any [default conventions](items.md#category-index-convention). - -The doc links can be specified relatively, e.g. if the category is generated with the `guides` directory, `"link": {"type": "doc", "id": "intro"}` will be resolved to the ID `guides/intro`, only falling back to `intro` if a doc with the former ID doesn't exist. - -You can also use `link: null` to opt out of default conventions and not generate any category index page. - -::: - -:::info - -The position metadata is only used **within a sidebar slice**: Docusaurus does not re-order other items of your sidebar. - -::: - -## Using number prefixes {#using-number-prefixes} - -A simple way to order an autogenerated sidebar is to prefix docs and folders by number prefixes, which also makes them appear in the file system in the same order when sorted by file name: - -```bash -docs -├── 01-Intro.md -├── 02-Tutorial Easy -│ ├── 01-First Part.md -│ ├── 02-Second Part.md -│ └── 03-End.md -├── 03-Tutorial Hard -│ ├── 01-First Part.md -│ ├── 02-Second Part.md -│ ├── 03-Third Part.md -│ └── 04-End.md -└── 04-End.md -``` - -To make it **easier to adopt**, Docusaurus supports **multiple number prefix patterns**. - -By default, Docusaurus will **remove the number prefix** from the doc id, title, label, and URL paths. - -:::caution - -**Prefer using [additional metadata](#autogenerated-sidebar-metadata)**. - -Updating a number prefix can be annoying, as it can require **updating multiple existing Markdown links**: - -```diff title="docs/02-Tutorial Easy/01-First Part.md" -- Check the [Tutorial End](../04-End.md); -+ Check the [Tutorial End](../05-End.md); -``` - -::: - -## Customize the sidebar items generator {#customize-the-sidebar-items-generator} - -You can provide a custom `sidebarItemsGenerator` function in the docs plugin (or preset) config: - -```js title="docusaurus.config.js" -module.exports = { - plugins: [ - [ - '@docusaurus/plugin-content-docs', - { - // highlight-start - async sidebarItemsGenerator({ - defaultSidebarItemsGenerator, - numberPrefixParser, - item, - version, - docs, - categoriesMetadata, - isCategoryIndex, - }) { - // Example: return an hardcoded list of static sidebar items - return [ - {type: 'doc', id: 'doc1'}, - {type: 'doc', id: 'doc2'}, - ]; - }, - // highlight-end - }, - ], - ], -}; -``` - -:::tip - -**Re-use and enhance the default generator** instead of writing a generator from scratch: [the default generator we provide](https://github.com/facebook/docusaurus/blob/main/packages/docusaurus-plugin-content-docs/src/sidebars/generator.ts) is 250 lines long. - -**Add, update, filter, re-order** the sidebar items according to your use case: - -```js title="docusaurus.config.js" -// highlight-start -// Reverse the sidebar items ordering (including nested category items) -function reverseSidebarItems(items) { - // Reverse items in categories - const result = items.map((item) => { - if (item.type === 'category') { - return {...item, items: reverseSidebarItems(item.items)}; - } - return item; - }); - // Reverse items at current level - result.reverse(); - return result; -} -// highlight-end - -module.exports = { - plugins: [ - [ - '@docusaurus/plugin-content-docs', - { - // highlight-start - async sidebarItemsGenerator({defaultSidebarItemsGenerator, ...args}) { - const sidebarItems = await defaultSidebarItemsGenerator(args); - return reverseSidebarItems(sidebarItems); - }, - // highlight-end - }, - ], - ], -}; -``` - -::: diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/index.md b/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/index.md deleted file mode 100644 index 06eb5a91b3b9..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/index.md +++ /dev/null @@ -1,210 +0,0 @@ ---- -slug: /sidebar ---- - -# Sidebar - -Creating a sidebar is useful to: - -- Group multiple **related documents** -- **Display a sidebar** on each of those documents -- Provide **paginated navigation**, with next/previous button - -To use sidebars on your Docusaurus site: - -1. Define a file that exports a dictionary of [sidebar objects](#sidebar-object). -2. Pass this object into the `@docusaurus/plugin-docs` plugin directly or via `@docusaurus/preset-classic`. - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - docs: { - // highlight-next-line - sidebarPath: require.resolve('./sidebars.js'), - }, - }, - ], - ], -}; -``` - -This section serves as an overview of miscellaneous features of the doc sidebar. In the following sections, we will more systematically introduce the following concepts: - -```mdx-code-block -import DocCardList from '@theme/DocCardList'; -import {useCurrentSidebarCategory} from '@docusaurus/theme-common'; - - -``` - -## Default sidebar {#default-sidebar} - -If the `sidebarPath` is unspecified, Docusaurus [automatically generates a sidebar](autogenerated.md) for you, by using the filesystem structure of the `docs` folder: - -```js title="sidebars.js" -module.exports = { - mySidebar: [ - { - type: 'autogenerated', - dirName: '.', // generate sidebar from the docs folder (or versioned_docs/) - }, - ], -}; -``` - -You can also define your sidebars explicitly. - -## Sidebar object {#sidebar-object} - -A sidebar at its crux is a hierarchy of categories, doc links, and other hyperlinks. - -```ts -type Sidebar = - // Normal syntax - | SidebarItem[] - // Shorthand syntax - | {[categoryLabel: string]: SidebarItem[]}; -``` - -For example: - -```js title="sidebars.js" -module.exports = { - mySidebar: [ - { - type: 'category', - label: 'Getting Started', - items: [ - { - type: 'doc', - id: 'doc1', - }, - ], - }, - { - type: 'category', - label: 'Docusaurus', - items: [ - { - type: 'doc', - id: 'doc2', - }, - { - type: 'doc', - id: 'doc3', - }, - ], - }, - { - type: 'link', - label: 'Learn more', - href: 'https://example.com', - }, - ], -}; -``` - -This is a sidebars file that exports one sidebar, called `mySidebar`. It has three top-level items: two categories and one external link. Within each category, there are a few doc links. - -A sidebars file can contain [**multiple sidebar objects**](multiple-sidebars.md), identified by their object keys. - -```ts -type SidebarsFile = { - [sidebarID: string]: Sidebar; -}; -``` - -## Theme configuration {#theme-configuration} - -### Hideable sidebar {#hideable-sidebar} - -By enabling the `themeConfig.docs.sidebar.hideable` option, you can make the entire sidebar hideable, allowing users to better focus on the content. This is especially useful when content is consumed on medium-sized screens (e.g. tablets). - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - // highlight-start - docs: { - sidebar: { - hideable: true, - }, - }, - // highlight-end - }, -}; -``` - -### Auto-collapse sidebar categories {#auto-collapse-sidebar-categories} - -The `themeConfig.docs.sidebar.autoCollapseCategories` option would collapse all sibling categories when expanding one category. This saves the user from having too many categories open and helps them focus on the selected section. - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - // highlight-start - docs: { - sidebar: { - autoCollapseCategories: true, - }, - }, - // highlight-end - }, -}; -``` - -## Passing custom props {#passing-custom-props} - -To pass in custom props to a swizzled sidebar item, add the optional `customProps` object to any of the items: - -```js -{ - type: 'doc', - id: 'doc1', - customProps: { - /* props */ - }, -}; -``` - -## Sidebar Breadcrumbs {#sidebar-breadcrumbs} - -By default, breadcrumbs are rendered at the top, using the "sidebar path" of the current page. - -This behavior can be disabled with plugin options: - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - docs: { - // highlight-next-line - breadcrumbs: false, - }, - }, - ], - ], -}; -``` - -## Complex sidebars example {#complex-sidebars-example} - -A real-world example from the Docusaurus site: - -```mdx-code-block -import CodeBlock from '@theme/CodeBlock'; - - - {require('!!raw-loader!@site/sidebars.js') - .default - .split('\n') - // remove comments - .map((line) => !['//','/*','*'].some(commentPattern => line.trim().startsWith(commentPattern)) && line) - .filter(Boolean) - .join('\n')} - -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/items.md b/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/items.md deleted file mode 100644 index fa7af72ca9be..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/items.md +++ /dev/null @@ -1,611 +0,0 @@ ---- -toc_max_heading_level: 4 -slug: /sidebar/items ---- - -# Sidebar items - -```mdx-code-block -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -``` - -We have introduced three types of item types in the example in the previous section: `doc`, `category`, and `link`, whose usages are fairly intuitive. We will formally introduce their APIs. There's also a fourth type: `autogenerated`, which we will explain in detail later. - -- **[Doc](#sidebar-item-doc)**: link to a doc page, associating it with the sidebar -- **[Link](#sidebar-item-link)**: link to any internal or external page -- **[Category](#sidebar-item-category)**: creates a dropdown of sidebar items -- **[Autogenerated](autogenerated.md)**: generate a sidebar slice automatically -- **[HTML](#sidebar-item-html)**: renders pure HTML in the item's position -- **[\*Ref](multiple-sidebars.md#sidebar-item-ref)**: link to a doc page, without making the item take part in navigation generation - -## Doc: link to a doc {#sidebar-item-doc} - -Use the `doc` type to link to a doc page and assign that doc to a sidebar: - -```ts -type SidebarItemDoc = - // Normal syntax - | { - type: 'doc'; - id: string; - label: string; // Sidebar label text - className?: string; // Class name for sidebar label - customProps?: Record; // Custom props - } - - // Shorthand syntax - | string; // docId shortcut -``` - -Example: - -```js title="sidebars.js" -module.exports = { - mySidebar: [ - // Normal syntax: - // highlight-start - { - type: 'doc', - id: 'doc1', // document ID - label: 'Getting started', // sidebar label - }, - // highlight-end - - // Shorthand syntax: - // highlight-start - 'doc2', // document ID - // highlight-end - ], -}; -``` - -If you use the doc shorthand or [autogenerated](#sidebar-item-autogenerated) sidebar, you would lose the ability to customize the sidebar label through item definition. You can, however, use the `sidebar_label` Markdown front matter within that doc, which has higher precedence over the `label` key in the sidebar item. Similarly, you can use `sidebar_custom_props` to declare custom metadata for a doc page. - -:::note - -A `doc` item sets an [implicit sidebar association](#sidebar-association). Don't assign the same doc to multiple sidebars: change the type to `ref` instead. - -::: - -:::tip - -Sidebar custom props is a useful way to propagate arbitrary doc metadata to the client side, so you can get additional information when using any doc-related hook that fetches a doc object. - -::: - -## Link: link to any page {#sidebar-item-link} - -Use the `link` type to link to any page (internal or external) that is not a doc. - -```ts -type SidebarItemLink = { - type: 'link'; - label: string; - href: string; - className?: string; -}; -``` - -Example: - -```js title="sidebars.js" -module.exports = { - myLinksSidebar: [ - // highlight-start - // External link - { - type: 'link', - label: 'Facebook', // The link label - href: 'https://facebook.com', // The external URL - }, - // highlight-end - - // highlight-start - // Internal link - { - type: 'link', - label: 'Home', // The link label - href: '/', // The internal path - }, - // highlight-end - ], -}; -``` - -## HTML: render custom markup {#sidebar-item-html} - -Use the `html` type to render custom HTML within the item's `
  • ` tag. - -This can be useful for inserting custom items such as dividers, section titles, ads, and images. - -```ts -type SidebarItemHtml = { - type: 'html'; - value: string; - defaultStyle?: boolean; // Use default menu item styles - className?: string; -}; -``` - -Example: - -```js title="sidebars.js" -module.exports = { - myHtmlSidebar: [ - // highlight-start - { - type: 'html', - value: 'Sponsor', // The HTML to be rendered - defaultStyle: true, // Use the default menu item styling - }, - // highlight-end - ], -}; -``` - -:::tip - -The menu item is already wrapped in an `
  • ` tag, so if your custom item is simple, such as a title, just supply a string as the value and use the `className` property to style it: - -```js title="sidebars.js" -module.exports = { - myHtmlSidebar: [ - { - type: 'html', - value: 'Core concepts', - className: 'sidebar-title', - }, - ], -}; -``` - -::: - -## Category: create a hierarchy {#sidebar-item-category} - -Use the `category` type to create a hierarchy of sidebar items. - -```ts -type SidebarItemCategory = { - type: 'category'; - label: string; // Sidebar label text. - items: SidebarItem[]; // Array of sidebar items. - className?: string; - - // Category options: - collapsible: boolean; // Set the category to be collapsible - collapsed: boolean; // Set the category to be initially collapsed or open by default - link: SidebarItemCategoryLinkDoc | SidebarItemCategoryLinkGeneratedIndex; -}; -``` - -Example: - -```js title="sidebars.js" -module.exports = { - docs: [ - { - type: 'category', - label: 'Guides', - collapsible: true, - collapsed: false, - items: [ - 'creating-pages', - { - type: 'category', - label: 'Docs', - items: ['introduction', 'sidebar', 'markdown-features', 'versioning'], - }, - ], - }, - ], -}; -``` - -:::tip - -Use the [**shorthand syntax**](#category-shorthand) when you don't need customizations: - -```js title="sidebars.js" -module.exports = { - docs: { - Guides: [ - 'creating-pages', - { - Docs: ['introduction', 'sidebar', 'markdown-features', 'versioning'], - }, - ], - }, -}; -``` - -::: - -### Category links {#category-link} - -With category links, clicking on a category can navigate you to another page. - -:::tip - -Use category links to introduce a category of documents. - -Autogenerated categories can use the [`_category_.yml`](./autogenerated.md#category-item-metadata) file to declare the link. - -::: - -#### Generated index page {#generated-index-page} - -You can auto-generate an index page that displays all the direct children of this category. The `slug` allows you to customize the generated page's route, which defaults to `/category/[categoryName]`. - -```js title="sidebars.js" -module.exports = { - docs: [ - { - type: 'category', - label: 'Guides', - // highlight-start - link: { - type: 'generated-index', - title: 'Docusaurus Guides', - description: 'Learn about the most important Docusaurus concepts!', - slug: '/category/docusaurus-guides', - keywords: ['guides'], - image: '/img/docusaurus.png', - }, - // highlight-end - items: ['pages', 'docs', 'blog', 'search'], - }, - ], -}; -``` - -See it in action on the [Docusaurus Guides page](/docs/category/guides). - -:::tip - -Use `generated-index` links as a quick way to get an introductory document. - -::: - -#### Doc link {#category-doc-link} - -A category can link to an existing document. - -```js title="sidebars.js" -module.exports = { - docs: [ - { - type: 'category', - label: 'Guides', - // highlight-start - link: {type: 'doc', id: 'introduction'}, - // highlight-end - items: ['pages', 'docs', 'blog', 'search'], - }, - ], -}; -``` - -See it in action on the [i18n introduction page](../../../i18n/i18n-introduction.md). - -#### Embedding generated index in doc page {#embedding-generated-index-in-doc-page} - -You can embed the generated cards list in a normal doc page as well, as long as the doc is used as a category index page. To do so, you need to use the `DocCardList` component, paired with the `useCurrentSidebarCategory` hook. - -```jsx title="a-category-index-page.md" -import DocCardList from '@theme/DocCardList'; -import {useCurrentSidebarCategory} from '@docusaurus/theme-common'; - -In this section, we will introduce the following concepts: - - -``` - -See this in action on the [sidebar guides page](index.md). - -### Collapsible categories {#collapsible-categories} - -We support the option to expand/collapse categories. Categories are collapsible by default, but you can disable collapsing with `collapsible: false`. - -```js title="sidebars.js" -module.exports = { - docs: [ - { - type: 'category', - label: 'Guides', - items: [ - 'creating-pages', - { - type: 'category', - // highlight-next-line - collapsible: false, - label: 'Docs', - items: ['introduction', 'sidebar', 'markdown-features', 'versioning'], - }, - ], - }, - ], -}; -``` - -To make all categories non-collapsible by default, set the `sidebarCollapsible` option in `plugin-content-docs` to `false`: - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - docs: { - // highlight-next-line - sidebarCollapsible: false, - }, - }, - ], - ], -}; -``` - -:::note - -The option in `sidebars.js` takes precedence over plugin configuration, so it is possible to make certain categories collapsible when `sidebarCollapsible` is set to `false` globally. - -::: - -### Expanded categories by default {#expanded-categories-by-default} - -Collapsible categories are collapsed by default. If you want them to be expanded on the first render, you can set `collapsed` to `false`: - -```js title="sidebars.js" -module.exports = { - docs: { - Guides: [ - 'creating-pages', - { - type: 'category', - label: 'Docs', - // highlight-next-line - collapsed: false, - items: ['markdown-features', 'sidebar', 'versioning'], - }, - ], - }, -}; -``` - -Similar to `collapsible`, you can also set the global configuration `options.sidebarCollapsed` to `false`. Individual `collapsed` options in `sidebars.js` will still take precedence over this configuration. - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - [ - '@docusaurus/preset-classic', - { - docs: { - // highlight-next-line - sidebarCollapsed: false, - }, - }, - ], - ], -}; -``` - -:::caution - -When a category has `collapsed: true` but `collapsible: false` (either through `sidebars.js` or through plugin configuration), the latter takes precedence and the category is still rendered as expanded. - -::: - -## Using shorthands {#using-shorthands} - -You can express typical sidebar items without much customization more concisely with **shorthand syntaxes**. There are two parts to this: [**doc shorthand**](#doc-shorthand) and [**category shorthand**](#category-shorthand). - -### Doc shorthand {#doc-shorthand} - -An item with type `doc` can be simply a string representing its ID: - -```mdx-code-block - - -``` - -```js title="sidebars.js" -module.exports = { - sidebar: [ - // highlight-start - { - type: 'doc', - id: 'myDoc', - }, - // highlight-end - ], -}; -``` - -```mdx-code-block - - -``` - -```js title="sidebars.js" -module.exports = { - sidebar: [ - // highlight-start - 'myDoc', - // highlight-end - ], -}; -``` - -```mdx-code-block - - -``` - -So it's possible to simplify the example above to: - -```js title="sidebars.js" -module.exports = { - mySidebar: [ - { - type: 'category', - label: 'Getting Started', - items: [ - // highlight-next-line - 'doc1', - ], - }, - { - type: 'category', - label: 'Docusaurus', - items: [ - // highlight-start - 'doc2', - 'doc3', - // highlight-end - ], - }, - { - type: 'link', - label: 'Learn more', - href: 'https://example.com', - }, - ], -}; -``` - -### Category shorthand {#category-shorthand} - -A category item can be represented by an object whose key is its label, and the value is an array of subitems. - -```mdx-code-block - - -``` - -```js title="sidebars.js" -module.exports = { - sidebar: [ - // highlight-start - { - type: 'category', - label: 'Getting started', - items: ['doc1', 'doc2'], - }, - // highlight-end - ], -}; -``` - -```mdx-code-block - - -``` - -```js title="sidebars.js" -module.exports = { - sidebar: [ - // highlight-start - { - 'Getting started': ['doc1', 'doc2'], - }, - // highlight-end - ], -}; -``` - -```mdx-code-block - - -``` - -This permits us to simplify that example to: - -```js title="sidebars.js" -module.exports = { - mySidebar: [ - // highlight-start - { - 'Getting started': ['doc1'], - }, - { - Docusaurus: ['doc2', 'doc3'], - }, - // highlight-end - { - type: 'link', - label: 'Learn more', - href: 'https://example.com', - }, - ], -}; -``` - -Each shorthand object after this transformation will contain exactly one entry. Now consider the further simplified example below: - -```js title="sidebars.js" -module.exports = { - mySidebar: [ - // highlight-start - { - 'Getting started': ['doc1'], - Docusaurus: ['doc2', 'doc3'], - }, - // highlight-end - { - type: 'link', - label: 'Learn more', - href: 'https://example.com', - }, - ], -}; -``` - -Note how the two consecutive category shorthands are compressed into one object with two entries. This syntax generates a **sidebar slice**: you shouldn't see that object as one bulk item—this object is unwrapped, with each entry becoming a separate item, and they spliced together with the rest of the items (in this case, the "Learn more" link) to form the final sidebar level. Sidebar slices are also important when discussing [autogenerated sidebars](autogenerated.md). - -Wherever you have an array of items that is reduced to one category shorthand, you can omit that enclosing array as well. - -```mdx-code-block - - -``` - -```js title="sidebars.js" -module.exports = { - sidebar: [ - { - 'Getting started': ['doc1'], - Docusaurus: [ - { - 'Basic guides': ['doc2', 'doc3'], - 'Advanced guides': ['doc4', 'doc5'], - }, - ], - }, - ], -}; -``` - -```mdx-code-block - - -``` - -```js title="sidebars.js" -module.exports = { - sidebar: { - 'Getting started': ['doc1'], - Docusaurus: { - 'Basic guides': ['doc2', 'doc3'], - 'Advanced guides': ['doc4', 'doc5'], - }, - }, -}; -``` - -```mdx-code-block - - -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/multiple-sidebars.md b/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/multiple-sidebars.md deleted file mode 100644 index b97e4b5d1234..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/sidebar/multiple-sidebars.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -slug: /sidebar/multiple-sidebars ---- - -# Using multiple sidebars - -You can create a sidebar for each **set of Markdown files** that you want to **group together**. - -:::tip - -The Docusaurus site is a good example of using multiple sidebars: - -- [Docs](../../../introduction.md) -- [API](../../../cli.md) - -::: - -Consider this example: - -```js title="sidebars.js" -module.exports = { - tutorialSidebar: { - 'Category A': ['doc1', 'doc2'], - }, - apiSidebar: ['doc3', 'doc4'], -}; -``` - -When browsing `doc1` or `doc2`, the `tutorialSidebar` will be displayed; when browsing `doc3` or `doc4`, the `apiSidebar` will be displayed. - -## Understanding sidebar association {#sidebar-association} - -Following the example above, if a `commonDoc` is included in both sidebars: - -```js title="sidebars.js" -module.exports = { - tutorialSidebar: { - 'Category A': ['doc1', 'doc2', 'commonDoc'], - }, - apiSidebar: ['doc3', 'doc4', 'commonDoc'], -}; -``` - -How does Docusaurus know which sidebar to display when browsing `commonDoc`? Answer: it doesn't, and we don't guarantee which sidebar it will pick. - -When you add doc Y to sidebar X, it creates a two-way binding: sidebar X contains a link to doc Y, and when browsing doc Y, sidebar X will be displayed. But sometimes, we want to break either implicit binding: - -1. _How do I generate a link to doc Y in sidebar X without making sidebar X displayed on Y?_ For example, when I include doc Y in multiple sidebars as in the example above, and I want to explicitly tell Docusaurus to display one sidebar? -2. _How do I make sidebar X displayed when browsing doc Y, but sidebar X shouldn't contain the link to Y?_ For example, when Y is a "doc home page" and the sidebar is purely used for navigation? - -Front matter option `displayed_sidebar` will forcibly set the sidebar association. For the same example, you can still use doc shorthands without any special configuration: - -```js title="sidebars.js" -module.exports = { - tutorialSidebar: { - 'Category A': ['doc1', 'doc2'], - }, - apiSidebar: ['doc3', 'doc4'], -}; -``` - -And then add a front matter: - -```md title="commonDoc.md" ---- -displayed_sidebar: apiSidebar ---- -``` - -Which explicitly tells Docusaurus to display `apiSidebar` when browsing `commonDoc`. Using the same method, you can make sidebar X which doesn't contain doc Y appear on doc Y: - -```md title="home.md" ---- -displayed_sidebar: tutorialSidebar ---- -``` - -Even when `tutorialSidebar` doesn't contain a link to `home`, it will still be displayed when viewing `home`. - -If you set `displayed_sidebar: null`, no sidebar will be displayed whatsoever on this page, and subsequently, no pagination either. - -## Generating pagination {#generating-pagination} - -Docusaurus uses the sidebar to generate the "next" and "previous" pagination links at the bottom of each doc page. It strictly uses the sidebar that is displayed: if no sidebar is associated, it doesn't generate pagination either. However, the docs linked as "next" and "previous" are not guaranteed to display the same sidebar: they are included in this sidebar, but in their front matter, they may have a different `displayed_sidebar`. - -If a sidebar is displayed by setting `displayed_sidebar` front matter, and this sidebar doesn't contain the doc itself, no pagination is displayed. - -You can customize pagination with front matter `pagination_next` and `pagination_prev`. Consider this sidebar: - -```js title="sidebars.js" -module.exports = { - tutorial: [ - 'introduction', - { - installation: ['windows', 'linux', 'macos'], - }, - 'getting-started', - ], -}; -``` - -The pagination next link on "windows" points to "linux", but that doesn't make sense: you would want readers to proceed to "getting started" after installation. In this case, you can set the pagination manually: - -```md title="windows.md" ---- -# highlight-next-line -pagination_next: getting-started ---- - -# Installation on Windows -``` - -You can also disable displaying a pagination link with `pagination_next: null` or `pagination_prev: null`. - -The pagination label by default is the sidebar label. You can use the front matter `pagination_label` to customize how this doc appears in the pagination. - -## The `ref` item {#sidebar-item-ref} - -The `ref` type is identical to the [`doc` type](#sidebar-item-doc) in every way, except that it doesn't participate in generating navigation metadata. It only registers itself as a link. When [generating pagination](#generating-pagination) and [displaying sidebar](#sidebar-association), `ref` items are completely ignored. - -It is particularly useful where you wish to link to the same document from multiple sidebars. The document only belongs to one sidebar (the one where it's registered as `type: 'doc'` or from an autogenerated directory), but its link will appear in all sidebars that it's registered in. - -Consider this example: - -```js title="sidebars.js" -module.exports = { - tutorialSidebar: { - 'Category A': [ - 'doc1', - 'doc2', - // highlight-next-line - {type: 'ref', id: 'commonDoc'}, - 'doc5', - ], - }, - apiSidebar: ['doc3', 'doc4', 'commonDoc'], -}; -} -``` - -You can think of the `ref` type as the equivalent to doing the following: - -- Setting `displayed_sidebar: tutorialSidebar` for `commonDoc` (`ref` is ignored in sidebar association) -- Setting `pagination_next: doc5` for `doc2` and setting `pagination_prev: doc2` for `doc5` (`ref` is ignored in pagination generation) diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/versioning.md b/website/versioned_docs/version-2.0.0-rc.1/guides/docs/versioning.md deleted file mode 100644 index d2b3cd4f0a34..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/docs/versioning.md +++ /dev/null @@ -1,286 +0,0 @@ ---- -slug: /versioning ---- - -# Versioning - -You can use the versioning CLI to create a new documentation version based on the latest content in the `docs` directory. That specific set of documentation will then be preserved and accessible even as the documentation in the `docs` directory continues to evolve. - -```mdx-code-block -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -``` - -:::caution - -Think about it before starting to version your documentation - it can become difficult for contributors to help improve it! - -::: - -Most of the time, you don't need versioning as it will just increase your build time, and introduce complexity to your codebase. Versioning is **best suited for websites with high-traffic and rapid changes to documentation between versions**. If your documentation rarely changes, don't add versioning to your documentation. - -To better understand how versioning works and see if it suits your needs, you can read on below. - -## Overview {#overview} - -A typical versioned doc site looks like below: - -```bash -website -├── sidebars.json # sidebar for the current docs version -├── docs # docs directory for the current docs version -│ ├── foo -│ │ └── bar.md # https://mysite.com/docs/next/foo/bar -│ └── hello.md # https://mysite.com/docs/next/hello -├── versions.json # file to indicate what versions are available -├── versioned_docs -│ ├── version-1.1.0 -│ │ ├── foo -│ │ │ └── bar.md # https://mysite.com/docs/foo/bar -│ │ └── hello.md -│ └── version-1.0.0 -│ ├── foo -│ │ └── bar.md # https://mysite.com/docs/1.0.0/foo/bar -│ └── hello.md -├── versioned_sidebars -│ ├── version-1.1.0-sidebars.json -│ └── version-1.0.0-sidebars.json -├── docusaurus.config.js -└── package.json -``` - -The `versions.json` file is a list of version names, ordered from newest to oldest. - -The table below explains how a versioned file maps to its version and the generated URL. - -| Path | Version | URL | -| --------------------------------------- | -------------- | ----------------- | -| `versioned_docs/version-1.0.0/hello.md` | 1.0.0 | /docs/1.0.0/hello | -| `versioned_docs/version-1.1.0/hello.md` | 1.1.0 (latest) | /docs/hello | -| `docs/hello.md` | current | /docs/next/hello | - -:::tip - -The files in the `docs` directory belong to the `current` docs version. - -By default, the `current` docs version is labeled as `Next` and hosted under `/docs/next/*`, but it is entirely configurable to fit your project's release lifecycle. - -::: - -### Terminology {#terminology} - -Note the terminology we use here. - -
    -
    Current version
    -
    The version placed in the ./docs folder.
    -
    Latest version / last version
    -
    The version served by default for docs navbar items. Usually has path /docs.
    -
    - -Current version is defined by the **file system location**, while latest version is defined by the **the navigation behavior**. They may or may not be the same version! (And the default configuration, as shown in the table above, would treat them as different: current version at `/docs/next` and latest at `/docs`.) - -## Tutorials {#tutorials} - -### Tagging a new version {#tagging-a-new-version} - -1. First, make sure the current docs version (the `./docs` directory) is ready to be frozen. -2. Enter a new version number. - -```bash npm2yarn -npm run docusaurus docs:version 1.1.0 -``` - -When tagging a new version, the document versioning mechanism will: - -- Copy the full `docs/` folder contents into a new `versioned_docs/version-[versionName]/` folder. -- Create a versioned sidebars file based from your current [sidebar](docs-introduction.md#sidebar) configuration (if it exists) - saved as `versioned_sidebars/version-[versionName]-sidebars.json`. -- Append the new version number to `versions.json`. - -### Creating new docs {#creating-new-docs} - -1. Place the new file into the corresponding version folder. -2. Include the reference to the new file in the corresponding sidebar file according to the version number. - -```mdx-code-block - - -``` - -```bash -# The new file. -docs/new.md - -# Edit the corresponding sidebar file. -sidebars.js -``` - -```mdx-code-block - - -``` - -```bash -# The new file. -versioned_docs/version-1.0.0/new.md - -# Edit the corresponding sidebar file. -versioned_sidebars/version-1.0.0-sidebars.json -``` - -```mdx-code-block - - -``` - -### Updating an existing version {#updating-an-existing-version} - -You can update multiple docs versions at the same time because each directory in `versioned_docs/` represents specific routes when published. - -1. Edit any file. -2. Commit and push changes. -3. It will be published to the version. - -Example: When you change any file in `versioned_docs/version-2.6/`, it will only affect the docs for version `2.6`. - -### Deleting an existing version {#deleting-an-existing-version} - -You can delete/remove versions as well. - -1. Remove the version from `versions.json`. - -Example: - -```diff -[ - "2.0.0", - "1.9.0", - // highlight-next-line -- "1.8.0" -] -``` - -2. Delete the versioned docs directory. Example: `versioned_docs/version-1.8.0`. -3. Delete the versioned sidebars file. Example: `versioned_sidebars/version-1.8.0-sidebars.json`. - -## Configuring versioning behavior {#configuring-versioning-behavior} - -The "current" version is the version name for the `./docs` folder. There are different ways to manage versioning, but two very common patterns are: - -- You release v1, and start immediately working on v2 (including its docs). In this case, the **current version** is v2, which is in the `./docs` source folder, and can be browsed at `example.com/docs/next`. The **latest version** is v1, which is in the `./versioned_docs/version-1` source folder, and is browsed by most of your users at `example.com/docs`. -- You release v1, and will maintain it for some time before thinking about v2. In this case, the **current version** and **latest version** will both be point to v1, since the v2 docs doesn't even exist yet! - -Docusaurus defaults work great for the first use case. We will label the current version as "next" and you can even choose not to publish it. - -**For the 2nd use case**: if you release v1 and don't plan to work on v2 anytime soon, instead of versioning v1 and having to maintain the docs in 2 folders (`./docs` + `./versioned_docs/version-1.0.0`), you may consider "pretending" that the current version is a cut version by giving it a path and a label: - -```js title="docusaurus.config.js" -module.exports = { - presets: [ - '@docusaurus/preset-classic', - docs: { - // highlight-start - lastVersion: 'current', - versions: { - current: { - label: '1.0.0', - path: '1.0.0', - }, - }, - // highlight-end - }, - ], -}; -``` - -The docs in `./docs` will be served at `/docs/1.0.0` instead of `/docs/next`, and `1.0.0` will become the default version we link to in the navbar dropdown, and you will only need to maintain a single `./docs` folder. - -We offer these plugin options to customize versioning behavior: - -- `disableVersioning`: Explicitly disable versioning even with versions. This will make the site only include the current version. -- `includeCurrentVersion`: Include the current version (the `./docs` folder) of your docs. - - **Tip**: turn it off if the current version is a work-in-progress, not ready to be published. -- `lastVersion`: Sets which version "latest version" (the `/docs` route) refers to. - - **Tip**: `lastVersion: 'current'` makes sense if your current version refers to a major version that's constantly patched and released. The actual route base path and label of the latest version are configurable. -- `onlyIncludeVersions`: Defines a subset of versions from `versions.json` to be deployed. - - **Tip**: limit to 2 or 3 versions in dev and deploy previews to improve startup and build time. -- `versions`: A dictionary of version metadata. For each version, you can customize the following: - - `label`: the label displayed in the versions dropdown and banner. - - `path`: the route base path of this version. By default, latest version has `/` and current version has `/next`. - - `banner`: one of `'none'`, `'unreleased'`, and `'unmaintained'`. Determines what's displayed at the top of every doc page. Any version above the latest version would be "unreleased", and any version below would be "unmaintained". - - `badge`: show a badge with the version name at the top of a doc of that version. - - `className`: add a custom `className` to the `` element of doc pages of that version. - -See [docs plugin configuration](../../api/plugins/plugin-content-docs.md#configuration) for more details. - -## Navbar items {#navbar-items} - -We offer several navbar items to help you quickly set up navigation without worrying about versioned routes. - -- [`doc`](../../api/themes/theme-configuration.md#navbar-doc-link): a link to a doc. -- [`docSidebar`](../../api/themes/theme-configuration.md#navbar-doc-sidebar): a link to the first item in a sidebar. -- [`docsVersion`](../../api/themes/theme-configuration.md#navbar-docs-version): a link to the main doc of the currently viewed version. -- [`docsVersionDropdown`](../../api/themes/theme-configuration.md#navbar-docs-version-dropdown): a dropdown containing all the versions available. - -These links would all look for an appropriate version to link to, in the following order: - -1. **Active version**: the version that the user is currently browsing, if she is on a page provided by this doc plugin. If she's not on a doc page, fall back to... -2. **Preferred version**: the version that the user last viewed. If there's no history, fall back to... -3. **Latest version**: the default version that we navigate to, configured by the `lastVersion` option. - -## Recommended practices {#recommended-practices} - -### Version your documentation only when needed {#version-your-documentation-only-when-needed} - -For example, you are building documentation for your npm package `foo` and you are currently in version 1.0.0. You then release a patch version for a minor bug fix and it's now 1.0.1. - -Should you cut a new documentation version 1.0.1? **You probably shouldn't**. 1.0.1 and 1.0.0 docs shouldn't differ according to semver because there are no new features!. Cutting a new version for it will only just create unnecessary duplicated files. - -### Keep the number of versions small {#keep-the-number-of-versions-small} - -As a good rule of thumb, try to keep the number of your versions below 10. You will **very likely** to have a lot of obsolete versioned documentation that nobody even reads anymore. For example, [Jest](https://jestjs.io/versions) is currently in version `27.4`, and only maintains several latest documentation versions with the lowest being `25.X`. Keep it small 😊 - -:::tip archive older versions - -If you deploy your site on a Jamstack provider (e.g. [Netlify](../../deployment.mdx)), the provider will save each production build as a snapshot under an immutable URL. You can include archived versions that will never be rebuilt as external links to these immutable URLs. The Jest website and the Docusaurus website both use such pattern to keep the number of actively built versions low. - -::: - -### Use absolute import within the docs {#use-absolute-import-within-the-docs} - -Don't use relative paths import within the docs. Because when we cut a version the paths no longer work (the nesting level is different, among other reasons). You can utilize the `@site` alias provided by Docusaurus that points to the `website` directory. Example: - -```diff -- import Foo from '../src/components/Foo'; -+ import Foo from '@site/src/components/Foo'; -``` - -### Link docs by file paths {#link-docs-by-file-paths} - -Refer to other docs by relative file paths with the `.md` extension, so that Docusaurus can rewrite them to actual URL paths during building. Files will be linked to the correct corresponding version. - -```md -The [@hello](hello.md#paginate) document is great! - -See the [Tutorial](../getting-started/tutorial.md) for more info. -``` - -### Global or versioned collocated assets {#global-or-versioned-collocated-assets} - -You should decide if assets like images and files are per-version or shared between versions. - -If your assets should be versioned, put them in the docs version, and use relative paths: - -```md -![img alt](./myImage.png) - -[download this file](./file.pdf) -``` - -If your assets are global, put them in `/static` and use absolute paths: - -```md -![img alt](/myImage.png) - -[download this file](/file.pdf) -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/_markdown-partial-example.mdx b/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/_markdown-partial-example.mdx deleted file mode 100644 index 5eb3f3bf117b..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/_markdown-partial-example.mdx +++ /dev/null @@ -1,3 +0,0 @@ -Hello {props.name} - -This is text some content from `_markdown-partial-example.md`. diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/markdown-features-admonitions.mdx b/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/markdown-features-admonitions.mdx deleted file mode 100644 index 719dd371c93b..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/markdown-features-admonitions.mdx +++ /dev/null @@ -1,206 +0,0 @@ ---- -id: admonitions -description: Handling admonitions/callouts in Docusaurus Markdown -slug: /markdown-features/admonitions ---- - -# Admonitions - -import BrowserWindow from '@site/src/components/BrowserWindow'; -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import Admonition from '@theme/Admonition'; - -In addition to the basic Markdown syntax, we use [remark-admonitions](https://github.com/elviswolcott/remark-admonitions) alongside MDX to add support for admonitions. Admonitions are wrapped by a set of 3 colons. - -Example: - -```md -:::note - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: - -:::tip - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: - -:::info - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: - -:::caution - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: - -:::danger - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: -``` - -```mdx-code-block - - -:::note - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: - -:::tip - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: - -:::info - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: - -:::caution - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: - -:::danger - -Some **content** with _Markdown_ `syntax`. Check [this `api`](#). - -::: - - -``` - -## Usage with Prettier {#usage-with-prettier} - -If you use [Prettier](https://prettier.io) to format your Markdown files, Prettier might auto-format your code to invalid admonition syntax. To avoid this problem, add empty lines around the starting and ending directives. This is also why the examples we show here all have empty lines around the content. - - -```md - -:::note - -Hello world - -::: - - -:::note -Hello world -::: - - -::: note Hello world::: -``` - -## Specifying title {#specifying-title} - -You may also specify an optional title - -```md -:::note Your Title - -Some **content** with _Markdown_ `syntax`. - -::: -``` - -```mdx-code-block - - -:::note Your Title - -Some **content** with _Markdown_ `syntax`. - -::: - - -``` - -## Admonitions with MDX {#admonitions-with-mdx} - -You can use MDX inside admonitions too! - -```jsx -import Tabs from '@theme/Tabs'; - -import TabItem from '@theme/TabItem'; - -:::tip Use tabs in admonitions - - - This is an apple 🍎 - This is an orange 🍊 - This is a banana 🍌 - - -::: -``` - -```mdx-code-block - - -:::tip Use tabs in admonitions - - - This is an apple 🍎 - This is an orange 🍊 - This is a banana 🍌 - - -::: - - -``` - -## Usage in JSX {#usage-in-jsx} - -Outside of Markdown, you can use the `@theme/Admonition` component to get the same output. - -```jsx title="MyReactPage.jsx" -import Admonition from '@theme/Admonition'; - -export default function MyReactPage() { - return ( -
    - -

    Some information

    -
    -
    - ); -} -``` - -The types that are accepted are the same as above: `note`, `tip`, `danger`, `info`, `caution`. Optionally, you can specify an icon by passing a JSX element or a string, or a title: - -```jsx title="MyReactPage.jsx" - -

    - Use plugins to introduce shorter syntax for the most commonly used JSX - elements in your project. -

    -
    -``` - -```mdx-code-block - - -

    - Use plugins to introduce shorter syntax for the most commonly used JSX - elements in your project. -

    -
    -
    -``` diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/markdown-features-assets.mdx b/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/markdown-features-assets.mdx deleted file mode 100644 index 58c875c810ef..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/markdown-features-assets.mdx +++ /dev/null @@ -1,234 +0,0 @@ ---- -id: assets -description: Handling assets in Docusaurus Markdown -slug: /markdown-features/assets ---- - -# Assets - -import BrowserWindow from '@site/src/components/BrowserWindow'; -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Sometimes you want to link to assets (e.g. docx files, images...) directly from Markdown files, and it is convenient to co-locate the asset next to the Markdown file using it. - -Let's imagine the following file structure: - -``` -# Your doc -/website/docs/myFeature.mdx - -# Some assets you want to use -/website/docs/assets/docusaurus-asset-example-banner.png -/website/docs/assets/docusaurus-asset-example.docx -``` - -## Images {#images} - -You can display images in three different ways: Markdown syntax, CJS require, or ES imports syntax. - -```mdx-code-block - - -``` - -Display images using simple Markdown syntax: - -```md -![Example banner](./assets/docusaurus-asset-example-banner.png) -``` - -```mdx-code-block - - -``` - -Display images using inline CommonJS `require` in JSX image tag: - -```jsx -Example banner -``` - -```mdx-code-block - - -``` - -Display images using ES `import` syntax and JSX image tag: - -```jsx -import myImageUrl from './assets/docusaurus-asset-example-banner.png'; - -Example banner; -``` - -```mdx-code-block - - -``` - -All of the above result in displaying the image: - - - -![My image alternative text](../../assets/docusaurus-asset-example-banner.png) - - - -:::note - -If you are using [@docusaurus/plugin-ideal-image](../../api/plugins/plugin-ideal-image.md), you need to use the dedicated image component, as documented. - -::: - -## Files {#files} - -In the same way, you can link to existing assets by `require`'ing them and using the returned URL in `video`s, `a` anchor links, etc. - -```md -# My Markdown page - -
    Download this docx - -or - -[Download this docx using Markdown](./assets/docusaurus-asset-example.docx) -``` - - - - - Download this docx - - -[Download this docx using Markdown](../../assets/docusaurus-asset-example.docx) - - - -:::info Markdown links are always file paths - -If you use the Markdown image or link syntax, all asset paths will be resolved as file paths by Docusaurus and automatically converted to `require()` calls. You don't need to use `require()` in Markdown unless you use the JSX syntax, which you do have to handle yourself. - -::: - -## Inline SVGs {#inline-svgs} - -Docusaurus supports inlining SVGs out of the box. - -```jsx -import DocusaurusSvg from './docusaurus.svg'; - -; -``` - - - -import DocusaurusSvg from '@site/static/img/docusaurus.svg'; - - - - - -This can be useful if you want to alter the part of the SVG image via CSS. For example, you can change one of the SVG colors based on the current theme. - -```jsx -import DocusaurusSvg from './docusaurus.svg'; - -; -``` - -```css -[data-theme='light'] .themedDocusaurus [fill='#FFFF50'] { - fill: greenyellow; -} - -[data-theme='dark'] .themedDocusaurus [fill='#FFFF50'] { - fill: seagreen; -} -``` - - - - - -## Themed Images {#themed-images} - -Docusaurus supports themed images: the `ThemedImage` component (included in the themes) allows you to switch the image source based on the current theme. - -```jsx -import ThemedImage from '@theme/ThemedImage'; - -; -``` - -```mdx-code-block -import useBaseUrl from '@docusaurus/useBaseUrl'; -import ThemedImage from '@theme/ThemedImage'; - - - - -``` - -### GitHub-style themed images {#github-style-themed-images} - -GitHub uses its own [image theming approach](https://github.blog/changelog/2021-11-24-specify-theme-context-for-images-in-markdown/) with path fragments, which you can easily implement yourself. - -To toggle the visibility of an image using the path fragment (for GitHub, it's `#gh-dark-mode-only` and `#gh-light-mode-only`), add the following to your custom CSS (you can also use your own suffix if you don't want to be coupled to GitHub): - -```css title="src/css/custom.css" -[data-theme='light'] img[src$='#gh-dark-mode-only'], -[data-theme='dark'] img[src$='#gh-light-mode-only'] { - display: none; -} -``` - -```md -![Docusaurus themed image](/img/docusaurus_keytar.svg#gh-light-mode-only)![Docusaurus themed image](/img/docusaurus_speed.svg#gh-dark-mode-only) -``` - - - -![Docusaurus themed image](/img/docusaurus_keytar.svg#gh-light-mode-only)![Docusaurus themed image](/img/docusaurus_speed.svg#gh-dark-mode-only) - - - -## Static assets {#static-assets} - -If a Markdown link or image has an absolute path, the path will be seen as a file path and will be resolved from the static directories. For example, if you have configured [static directories](../../static-assets.md) to be `['public', 'static']`, then for the following image: - -```md title="my-doc.md" -![An image from the static](/img/docusaurus.png) -``` - -Docusaurus will try to look for it in both `static/img/docusaurus.png` and `public/img/docusaurus.png`. The link will then be converted to a `require()` call instead of staying as a URL. This is desirable in two regards: - -1. You don't have to worry about the base URL, which Docusaurus will take care of when serving the asset; -2. The image enters Webpack's build pipeline and its name will be appended by a hash, which enables browsers to aggressively cache the image and improves your site's performance. - -If you intend to write URLs, you can use the `pathname://` protocol to disable automatic asset linking. - -```md -![banner](pathname:///img/docusaurus-asset-example-banner.png) -``` - -This link will be generated as `banner`, without any processing or file existence checking. diff --git a/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/markdown-features-code-blocks.mdx b/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/markdown-features-code-blocks.mdx deleted file mode 100644 index 99669971e064..000000000000 --- a/website/versioned_docs/version-2.0.0-rc.1/guides/markdown-features/markdown-features-code-blocks.mdx +++ /dev/null @@ -1,833 +0,0 @@ ---- -id: code-blocks -description: Handling code blocks in Docusaurus Markdown -slug: /markdown-features/code-blocks ---- - -# Code blocks - -import BrowserWindow from '@site/src/components/BrowserWindow'; -import CodeBlock from '@theme/CodeBlock'; - -Code blocks within documentation are super-powered 💪. - -## Code title {#code-title} - -You can add a title to the code block by adding a `title` key after the language (leave a space between them). - -````md -```jsx title="/src/components/HelloCodeTitle.js" -function HelloCodeTitle(props) { - return

    Hello, {props.name}

    ; -} -``` -```` - -```mdx-code-block - -``` - -```jsx title="/src/components/HelloCodeTitle.js" -function HelloCodeTitle(props) { - return

    Hello, {props.name}

    ; -} -``` - -```mdx-code-block -
    -``` - -## Syntax highlighting {#syntax-highlighting} - -Code blocks are text blocks wrapped around by strings of 3 backticks. You may check out [this reference](https://github.com/mdx-js/specification) for the specifications of MDX. - -````md -```js -console.log('Every repo must come with a mascot.'); -``` -```` - -Use the matching language meta string for your code block, and Docusaurus will pick up syntax highlighting automatically, powered by [Prism React Renderer](https://github.com/FormidableLabs/prism-react-renderer). - - - -```js -console.log('Every repo must come with a mascot.'); -``` - - - -### Theming {#theming} - -By default, the Prism [syntax highlighting theme](https://github.com/FormidableLabs/prism-react-renderer#theming) we use is [Palenight](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/themes/palenight.js). You can change this to another theme by passing `theme` field in `prism` as `themeConfig` in your docusaurus.config.js. - -For example, if you prefer to use the `dracula` highlighting theme: - -```js title="docusaurus.config.js" -module.exports = { - themeConfig: { - prism: { - // highlight-next-line - theme: require('prism-react-renderer/themes/dracula'), - }, - }, -}; -``` - -Because a Prism theme is just a JS object, you can also write your own theme if you are not satisfied with the default. Docusaurus enhances the `github` and `vsDark` themes to provide richer highlight, and you can check our implementations for the [light](https://github.com/facebook/docusaurus/blob/main/website/src/utils/prismLight.mjs) and [dark](https://github.com/facebook/docusaurus/blob/main/website/src/utils/prismDark.mjs) code block themes. - -### Supported Languages {#supported-languages} - -By default, Docusaurus comes with a subset of [commonly used languages](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/vendor/prism/includeLangs.js). - -:::caution - -Some popular languages like Java, C#, or PHP are not enabled by default. - -::: - -To add syntax highlighting for any of the other [Prism-supported languages](https://prismjs.com/#supported-languages), define it in an array of additional languages. - -:::note - -Each additional language has to be a valid Prism component name. For example, Prism would map the _language_ `cs` to `csharp`, but only `prism-csharp.js` exists as a _component_, so you need to use `additionalLanguages: ['csharp']`. You can look into `node_modules/prismjs/components` to find all components (languages) available. - -::: - -For example, if you want to add highlighting for the PowerShell language: - -```js title="docusaurus.config.js" -module.exports = { - // ... - themeConfig: { - prism: { - // highlight-next-line - additionalLanguages: ['powershell'], - }, - // ... - }, -}; -``` - -After adding `additionalLanguages`, restart Docusaurus. - -If you want to add highlighting for languages not yet supported by Prism, you can swizzle `prism-include-languages`: - -```bash npm2yarn -npm run swizzle @docusaurus/theme-classic prism-include-languages -``` - -It will produce `prism-include-languages.js` in your `src/theme` folder. You can add highlighting support for custom languages by editing `prism-include-languages.js`: - -```js title="src/theme/prism-include-languages.js" -const prismIncludeLanguages = (Prism) => { - // ... - - additionalLanguages.forEach((lang) => { - require(`prismjs/components/prism-${lang}`); - }); - - // highlight-next-line - require('/path/to/your/prism-language-definition'); - - // ... -}; -``` - -You can refer to [Prism's official language definitions](https://github.com/PrismJS/prism/tree/master/components) when you are writing your own language definitions. - -## Line highlighting {#line-highlighting} - -### Highlighting with comments {#highlighting-with-comments} - -You can use comments with `highlight-next-line`, `highlight-start`, and `highlight-end` to select which lines are highlighted. - -````md -```js -function HighlightSomeText(highlight) { - if (highlight) { - // highlight-next-line - return 'This text is highlighted!'; - } - - return 'Nothing highlighted'; -} - -function HighlightMoreText(highlight) { - // highlight-start - if (highlight) { - return 'This range is highlighted!'; - } - // highlight-end - - return 'Nothing highlighted'; -} -``` -```` - -```mdx-code-block - -``` - -```js -function HighlightSomeText(highlight) { - if (highlight) { - // highlight-next-line - return 'This text is highlighted!'; - } - - return 'Nothing highlighted'; -} - -function HighlightMoreText(highlight) { - // highlight-start - if (highlight) { - return 'This range is highlighted!'; - } - // highlight-end - - return 'Nothing highlighted'; -} -``` - -```mdx-code-block - -``` - -Supported commenting syntax: - -| Style | Syntax | -| ---------- | ------------------------ | -| C-style | `/* ... */` and `// ...` | -| JSX-style | `{/* ... */}` | -| Bash-style | `# ...` | -| HTML-style | `` | - -We will do our best to infer which set of comment styles to use based on the language, and default to allowing _all_ comment styles. If there's a comment style that is not currently supported, we are open to adding them! Pull requests welcome. Note that different comment styles have no semantic difference, only their content does. - -You can set your own background color for highlighted code line in your `src/css/custom.css` which will better fit to your selected syntax highlighting theme. The color given below works for the default highlighting theme (Palenight), so if you are using another theme, you will have to tweak the color accordingly. - -```css title="/src/css/custom.css" -:root { - --docusaurus-highlighted-code-line-bg: rgb(72, 77, 91); -} - -/* If you have a different syntax highlighting theme for dark mode. */ -[data-theme='dark'] { - /* Color which works with dark mode syntax highlighting theme */ - --docusaurus-highlighted-code-line-bg: rgb(100, 100, 100); -} -``` - -If you also need to style the highlighted code line in some other way, you can target on `theme-code-block-highlighted-line` CSS class. - -### Highlighting with metadata string {#highlighting-with-metadata-string} - -You can also specify highlighted line ranges within the language meta string (leave a space after the language). To highlight multiple lines, separate the line numbers by commas or use the range syntax to select a chunk of lines. This feature uses the `parse-number-range` library and you can find [more syntax](https://www.npmjs.com/package/parse-numeric-range) on their project details. - -````md -```jsx {1,4-6,11} -import React from 'react'; - -function MyComponent(props) { - if (props.isBar) { - return
    Bar
    ; - } - - return
    Foo
    ; -} - -export default MyComponent; -``` -```` - -```mdx-code-block - -``` - -```jsx {1,4-6,11} -import React from 'react'; - -function MyComponent(props) { - if (props.isBar) { - return
    Bar
    ; - } - - return
    Foo
    ; -} - -export default MyComponent; -``` - -```mdx-code-block -
    -``` - -:::tip prefer comments - -Prefer highlighting with comments where you can. By inlining highlight in the code, you don't have to manually count the lines if your code block becomes long. If you add/remove lines, you also don't have to offset your line ranges. - -````diff -- ```jsx {3} -+ ```jsx {4} - function HighlightSomeText(highlight) { - if (highlight) { -+ console.log('Highlighted text found'); - return 'This text is highlighted!'; - } - - return 'Nothing highlighted'; - } - ``` -```` - -Below, we will introduce how the magic comment system can be extended to define custom directives and their functionalities. The magic comments would only be parsed if a highlight metastring is not present. - -::: - -### Custom magic comments {#custom-magic-comments} - -`// highlight-next-line` and `// highlight-start` etc. are called "magic comments", because they will be parsed and removed, and their purposes are to add metadata to the next line, or the section that the pair of start- and end-comments enclose. - -You can declare custom magic comments through theme config. For example, you can register another magic comment that adds a `code-block-error-line` class name: - -```mdx-code-block - - -``` - -```js -module.exports = { - themeConfig: { - prism: { - magicComments: [ - // Remember to extend the default highlight class name as well! - { - className: 'theme-code-block-highlighted-line', - line: 'highlight-next-line', - block: {start: 'highlight-start', end: 'highlight-end'}, - }, - // highlight-start - { - className: 'code-block-error-line', - line: 'This will error', - }, - // highlight-end - ], - }, - }, -}; -``` - -```mdx-code-block - - -``` - -```css -.code-block-error-line { - background-color: #ff000020; - display: block; - margin: 0 calc(-1 * var(--ifm-pre-padding)); - padding: 0 var(--ifm-pre-padding); - border-left: 3px solid #ff000080; -} -``` - -```mdx-code-block - - -``` - -````md -In JavaScript, trying to access properties on `null` will error. - -```js -const name = null; -// This will error -console.log(name.toUpperCase()); -// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase') -``` -```` - -```mdx-code-block - - -``` - -```mdx-code-block - -``` - -In JavaScript, trying to access properties on `null` will error. - -```js -const name = null; -// This will error -console.log(name.toUpperCase()); -// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase') -``` - -```mdx-code-block - -``` - -If you use number ranges in metastring (the `{1,3-4}` syntax), Docusaurus will apply the **first `magicComments` entry**'s class name. This, by default, is `theme-code-block-highlighted-line`, but if you change the `magicComments` config and use a different entry as the first one, the meaning of the metastring range will change as well. - -You can disable the default line highlighting comments with `magicComments: []`. If there's no magic comment config, but Docusaurus encounters a code block containing a metastring range, it will error because there will be no class name to apply—the highlighting class name, after all, is just a magic comment entry. - -Every magic comment entry will contain three keys: `className` (required), `line`, which applies to the directly next line, or `block` (containing `start` and `end`), which applies to the entire block enclosed by the two comments. - -Using CSS to target the class can already do a lot, but you can unlock the full potential of this feature through [swizzling](../../swizzling.md). - -```bash npm2yarn -npm run swizzle @docusaurus/theme-classic CodeBlock/Line -``` - -The `Line` component will receive the list of class names, based on which you can conditionally render different markup. - -## Line numbering {#line-numbering} - -You can enable line numbering for your code block by using `showLineNumbers` key within the language meta string (don't forget to add space directly before the key). - -````md -```jsx {1,4-6,11} showLineNumbers -import React from 'react'; - -function MyComponent(props) { - if (props.isBar) { - return
    Bar
    ; - } - - return
    Foo
    ; -} - -export default MyComponent; -``` -```` - -```mdx-code-block - -``` - -```jsx {1,4-6,11} showLineNumbers -import React from 'react'; - -function MyComponent(props) { - if (props.isBar) { - return
    Bar
    ; - } - - return
    Foo
    ; -} - -export default MyComponent; -``` - -```mdx-code-block -
    -``` - -## Interactive code editor {#interactive-code-editor} - -(Powered by [React Live](https://github.com/FormidableLabs/react-live)) - -You can create an interactive coding editor with the `@docusaurus/theme-live-codeblock` plugin. First, add the plugin to your package. - -```bash npm2yarn -npm install --save @docusaurus/theme-live-codeblock -``` - -You will also need to add the plugin to your `docusaurus.config.js`. - -```js {3} -module.exports = { - // ... - themes: ['@docusaurus/theme-live-codeblock'], - // ... -}; -``` - -To use the plugin, create a code block with `live` attached to the language meta string. - -````md -```jsx live -function Clock(props) { - const [date, setDate] = useState(new Date()); - useEffect(() => { - const timerID = setInterval(() => tick(), 1000); - - return function cleanup() { - clearInterval(timerID); - }; - }); - - function tick() { - setDate(new Date()); - } - - return ( -
    -

    It is {date.toLocaleTimeString()}.

    -
    - ); -} -``` -```` - -The code block will be rendered as an interactive editor. Changes to the code will reflect on the result panel live. - -```mdx-code-block - -``` - -```jsx live -function Clock(props) { - const [date, setDate] = useState(new Date()); - useEffect(() => { - const timerID = setInterval(() => tick(), 1000); - - return function cleanup() { - clearInterval(timerID); - }; - }); - - function tick() { - setDate(new Date()); - } - - return ( -
    -

    It is {date.toLocaleTimeString()}.

    -
    - ); -} -``` - -```mdx-code-block -
    -``` - -### Imports {#imports} - -:::caution react-live and imports - -It is not possible to import components directly from the react-live code editor, you have to define available imports upfront. - -::: - -By default, all React imports are available. If you need more imports available, swizzle the react-live scope: - -```bash npm2yarn -npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope -- --eject -``` - -```jsx title="src/theme/ReactLiveScope/index.js" -import React from 'react'; - -// highlight-start -const ButtonExample = (props) => ( -