chore(v2): v2.0.0-alpha.56 (#2822)

This commit is contained in:
Alexey Pyltsyn 2020-05-27 20:04:12 +03:00 committed by GitHub
parent 6462e1c4da
commit 3cf1a7b9ef
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
29 changed files with 6088 additions and 0 deletions

View file

@ -1,5 +1,67 @@
# Docusaurus 2 Changelog
## 2.0.0-alpha.56
#### :boom: Breaking Change
- `docusaurus-theme-classic`
- [#2818](https://github.com/facebook/docusaurus/pull/2818) feat(v2): automatically add base url to logo link ([@lex111](https://github.com/lex111))
- `docusaurus-theme-classic`, `docusaurus-theme-search-algolia`
- [#2791](https://github.com/facebook/docusaurus/pull/2791) refactor(v2): show search icon only on mobiles ([@lex111](https://github.com/lex111))
- `docusaurus`
- [#2780](https://github.com/facebook/docusaurus/pull/2780) feat(v2): open external links in new tab by default ([@jknoxville](https://github.com/jknoxville))
#### :rocket: New Feature
- `docusaurus-types`, `docusaurus`
- [#2770](https://github.com/facebook/docusaurus/pull/2770) feat(v2): allow deploy without building website ([@lex111](https://github.com/lex111))
- `docusaurus-theme-classic`
- [#2818](https://github.com/facebook/docusaurus/pull/2818) feat(v2): automatically add base url to logo link ([@lex111](https://github.com/lex111))
#### :bug: Bug Fix
- `docusaurus-theme-classic`
- [#2645](https://github.com/facebook/docusaurus/pull/2645) fix(v2): enable scrolling for sidebar menu only ([@lex111](https://github.com/lex111))
- [#2800](https://github.com/facebook/docusaurus/pull/2800) fix(v2): make proper h1 font size on mobiles ([@lex111](https://github.com/lex111))
- `docusaurus`
- [#2788](https://github.com/facebook/docusaurus/pull/2788) fix(v2): use `require.resolve` for all webpack presets and plugins ([@SamChou19815](https://github.com/SamChou19815))
- `docusaurus-plugin-content-docs`
- [#2785](https://github.com/facebook/docusaurus/pull/2785) fix(v2): do not show sidebar on reserved docs home page ([@lex111](https://github.com/lex111))
- [#2777](https://github.com/facebook/docusaurus/pull/2777) fix(v2): check for docs homepage correctly ([@lex111](https://github.com/lex111))
#### :nail_care: Polish
- `docusaurus-theme-classic`
- [#2820](https://github.com/facebook/docusaurus/pull/2820) chore(v2): upgrade Infima to 0.2.0-alpha.12 ([@lex111](https://github.com/lex111))
- `docusaurus-theme-search-algolia`
- [#2814](https://github.com/facebook/docusaurus/pull/2814) refactor(v2): align search icon to center on mobiles ([@lex111](https://github.com/lex111))
- [#2799](https://github.com/facebook/docusaurus/pull/2799) refactor(v2): increase search input on medium screens ([@lex111](https://github.com/lex111))
- `docusaurus-init`
- [#2802](https://github.com/facebook/docusaurus/pull/2802) misc: minor improvements for init templates ([@lex111](https://github.com/lex111))
- `docusaurus-theme-classic`, `docusaurus-theme-search-algolia`
- [#2791](https://github.com/facebook/docusaurus/pull/2791) refactor(v2): show search icon only on mobiles ([@lex111](https://github.com/lex111))
- `docusaurus`
- [#2783](https://github.com/facebook/docusaurus/pull/2783) refactor(v2): make external links more secure ([@lex111](https://github.com/lex111))
#### :memo: Documentation
- [#2809](https://github.com/facebook/docusaurus/pull/2809) docs(v2): add mention on DocSearch when you run the crawler on your own ([@s-pace](https://github.com/s-pace))
#### :house: Internal
- [#2778](https://github.com/facebook/docusaurus/pull/2778) fix(v2): do not highlight root docs path in navbar ([@lex111](https://github.com/lex111))
#### Committers: 8
- Alexey Pyltsyn ([@lex111](https://github.com/lex111))
- James McShane ([@jmcshane](https://github.com/jmcshane))
- John Knox ([@jknoxville](https://github.com/jknoxville))
- Kasper Bøgebjerg Pedersen ([@kasperp](https://github.com/kasperp))
- Muhammad Ali ([@mrmuhammadali](https://github.com/mrmuhammadali))
- Piotr Baran ([@piotros](https://github.com/piotros))
- Sam Zhou ([@SamChou19815](https://github.com/SamChou19815))
- Sylvain Pace ([@s-pace](https://github.com/s-pace))
## 2.0.0-alpha.55
#### :boom: Breaking Change

View file

@ -0,0 +1,171 @@
---
id: blog
title: Blog
---
## Initial setup
To setup your site's blog, start by creating a `blog` directory.
Then, add a navbar link to your blog within `docusaurus.config.js`:
```js title="docusaurus.config.js"
module.exports = {
themeConfig: {
// ...
navbar: {
links: [
// ...
// highlight-next-line
{to: 'blog', label: 'Blog', position: 'left'}, // or position: 'right'
],
},
},
};
```
## Adding posts
To publish in the blog, create a file within the blog directory with a formatted name of `YYYY-MM-DD-my-blog-post-title.md`. The post date is extracted from the file name.
For example, at `my-website/blog/2019-09-05-hello-docusaurus-v2.md`:
```yml
---
title: Welcome Docusaurus v2
author: Joel Marcey
author_title: Co-creator of Docusaurus 1
author_url: https://github.com/JoelMarcey
author_image_url: https://graph.facebook.com/611217057/picture/?height=200&width=200
tags: [hello, docusaurus-v2]
---
Welcome to this blog. This blog is created with [**Docusaurus 2 alpha**](https://v2.docusaurus.io/).
<!--truncate-->
This is my first post on Docusaurus 2.
A whole bunch of exploration to follow.
```
## Header options
The only required field is `title`; however, we provide options to add author information to your blog post as well along with other options.
- `author` - The author name to be displayed.
- `author_url` - The URL that the author's name will be linked to. This could be a GitHub, Twitter, Facebook profile URL, etc.
- `author_image_url` - The URL to the author's thumbnail image.
- `author_title` - A description of the author.
- `title` - The blog post title.
- `tags` - A list of strings to tag to your post.
- `draft` - A boolean flag to indicate that the blog post is work in process and therefore should not be published yet. However, draft blog posts will be displayed during development.
## Summary truncation
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:
```yml
---
title: Truncation Example
---
All this will be part of the blog post summary.
Even this.
<!--truncate-->
But anything from here on down will not be.
Not this.
Or this.
```
## Feed
You can generate RSS/ Atom feed by passing feedOptions.
```ts
feedOptions?: {
type: 'rss' | 'atom' | 'all';
title?: string;
description?: string;
copyright: string;
language?: string; // possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
};
```
Example usage:
```js {8-11} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
feedOptions: {
type: 'all',
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`,
},
},
},
],
],
};
```
Accessing the feed:
The feed for RSS can be found at:
```text
https://{your-domain}/blog/rss.xml
```
and for Atom:
```text
https://{your-domain}/blog/atom.xml
```
## Advanced topics
### Blog-only mode
You can run your Docusaurus 2 site without a landing page and instead have your blog's post list page as the index page. Set the `routeBasePath` to be `'/'` to indicate it's the root path.
```js {9} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
path: './blog',
routeBasePath: '/', // Set this value to '/'.
},
},
],
],
};
```
:::note
Make sure there's no `index.js` page in `src/pages` or else there will be two files mapping to the same route!
:::
<!--
Adding a blog using the blog plugin.
References
---
- [source code](/packages/docusaurus-plugin-content-blog/src/index.js)
- [v1 doc](https://docusaurus.io/docs/en/next/adding-blog)
-->

View file

@ -0,0 +1,113 @@
---
id: cli
title: 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": {
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy"
}
}
```
## Docusaurus CLI commands
Below is a list of Docusaurus CLI commands and their usages:
<!-- TODO: init docs after the init command is implemented
### `docusaurus init`
The `docusaurus init` command is intended to be used with `docusaurus` installed globally:
```shell
$ yarn global add docusaurus
# or
$ npm install --global docusaurus
```
-->
### `docusaurus start`
Builds and serves a preview of your site locally with [Webpack Dev Server](https://webpack.js.org/configuration/dev-server).
#### 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 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. |
| `--poll` | `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). |
:::important
Please note that some functionality (for example, anchor links) will not work in development. The functionality will work as expected in production.
:::
### `docusaurus build`
Compiles your site for production.
#### Options
| 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. |
| `--no-minify` | `false` | Build website without minimizing JS/CSS bundles. |
### `docusaurus swizzle`
:::caution
We highly discourage swizzling of components until we've reached a Beta stage. The components APIs have been changing rapidly and are likely to keep changing until we reach Beta. Stick with the default appearance for now if possible to save yourself some potential pain in future.
:::
Change any Docusaurus theme components to your liking with `docusaurus swizzle`.
```shell
docusaurus swizzle <themeName> [componentName] [siteDir]
# Example (leaving out the siteDir to indicate this directory)
docusaurus swizzle @docusaurus/theme-classic DocSidebar
```
Running the command will copy the relevant theme files to your site folder. You may then make any changes to it and Docusaurus will use it instead of the one provided from the theme.
#### Options
| Name | Description |
| ------------------ | ------------------------------------- |
| `themeName` | The name of the theme you are using. |
| `swizzleComponent` | The name of the component to swizzle. |
To unswizzle a component, simply delete the files of the swizzled component.
<!--
TODO a separate section for swizzle tutorial.
To learn more about swizzling, check [here](#).
-->
### `docusaurus deploy`
Deploys your site with [GitHub Pages](https://pages.github.com/). Check out the docs on [deployment](deployment.md/#deploying-to-github-pages) for more details.
#### Options
| 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 custom deploy script. |

View file

@ -0,0 +1,151 @@
---
id: configuration
title: Configuration
---
Docusaurus has a unique take on configurations. We encourage you to congregate information of 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 be able to focus on documentation while still being able to customize the site.
## What goes into a `docusaurus.config.js`?
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:
- [Site metadata](#site-metadata)
- [Deployment configurations](#deployment-configurations)
- [Theme, plugin, and preset configurations](#theme-plugin-and-preset-configurations)
- [Custom configurations](#custom-configurations)
For exact reference to each of the configurable fields, you may refer to [**`docusaurus.config.js` API reference**](docusaurus.config.js.md).
### Site metadata
Site metadata contains the essential global metadata such as `title`, `url`, `baseUrl` and `favicon`.
They are used in a number of 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 such as `projectName` and `organizationName` are used when you deploy your site with the `deploy` command.
It is recommended to check the [deployment docs](deployment.md) for more information.
### Theme, plugin, and preset configurations
List the [theme](using-themes.md), [plugins](using-plugins.md), and [presets](presets.md) 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'],
};
```
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: [
[
'@docusaurus/plugin-content-blog',
{
path: 'blog',
routeBasePath: 'blog',
include: ['*.md', '*.mdx'],
// ...
},
],
'@docusaurus/plugin-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'),
},
},
],
],
};
```
For further help configuring themes, plugins, and presets, see [Using Themes](using-themes.md), [Using Plugins](using-plugins.md), and [Using Presets](presets.md).
### 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
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 context = useDocusaurusContext();
const {siteConfig = {}} = context;
// 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`.
:::

View file

@ -0,0 +1,190 @@
---
id: contributing
title: Contributing
---
[Docusaurus 2](https://v2.docusaurus.io/) is currently under alpha development. We have [early adopters who already started using it](/showcase). We are now welcoming contributors to collaborate on the next Docusaurus.
The [Open Source Guides](https://opensource.guide/) website has a collection of resources for individuals, communities, and companies who want to learn how to run and contribute to an open source project. Contributors and people new to open source alike will find the following guides especially useful:
- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
- [Building Welcoming Communities](https://opensource.guide/building-community/)
## [Code of Conduct](https://code.fb.com/codeofconduct)
Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.fb.com/codeofconduct) so that you can understand what actions will and will not be tolerated.
## Get involved
There are many ways to contribute to Docusaurus, and many of them do not involve writing any code. Here's a few ideas to get started:
- Start using Docusaurus 2! Go through the [Getting Started](installation.md) guides. Does everything work as expected? If not, we're always looking for improvements. Let us know by [opening an issue](#reporting-new-issues).
- Look through the [v2.0 issues](https://github.com/facebook/docusaurus/labels/v2). If you find an issue you would like to fix, [open a pull request](#your-first-pull-request). Issues tagged as [_Good first issue_](https://github.com/facebook/docusaurus/labels/Good%20first%20issue) are a good place to get started.
- Help us making the docs better. File an issue if you find anything that is confusing or can be improved. We also have [an umbrella issue for v2 docs](https://github.com/facebook/docusaurus/issues/1640) where we are planning and working on all v2 docs. You may adopt a doc piece there to work on.
- Take a look at the [features requested](https://github.com/facebook/docusaurus/labels/enhancement) by others in the community and consider opening a pull request if you see something you want to work on.
Contributions are very welcome. If you think you need help planning your contribution, please ping us on Twitter at [@docusaurus](https://twitter.com/docusaurus) and let us know you are looking for a bit of help.
### Join our Discord channel
To participate in Docusaurus 2 dev, join the [#docusaurus-2-dev](https://discord.gg/Je6Ash6) channel.
## Our development process
Docusaurus uses [GitHub](https://github.com/facebook/docusaurus) as its source of truth. The core team will be working directly there. All changes will be public from the beginning.
When a change made on GitHub is approved, it will be checked by our continuous integration system, CircleCI.
### Reporting new issues
When [opening a new issue](https://github.com/facebook/docusaurus/issues/new/choose), always make sure to fill out the issue template. **This step is very important!** Not doing so may result in your issue not managed in a timely fashion. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template.
- **One issue, one bug:** Please report a single bug per issue.
- **Provide reproduction steps:** List all the steps necessary to reproduce the issue. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort.
### Reporting bugs
We use [GitHub Issues](https://github.com/facebook/docusaurus/issues) for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you a are certain this is a new, unreported bug, you can submit a [bug report](#reporting-new-issues).
If you have questions about using Docusaurus, contact the Docusaurus Twitter account at [@docusaurus](https://twitter.com/docusaurus), and we will do our best to answer your questions.
You can also file issues as [feature requests or enhancements](https://github.com/facebook/docusaurus/labels/feature). If you see anything you'd like to be implemented, create an issue with [feature template](https://raw.githubusercontent.com/facebook/docusaurus/master/.github/ISSUE_TEMPLATE/feature.md/)
### Reporting security bugs
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. With that in mind, please do not file public issues; go through the process outlined on that page.
## Working on Docusaurus code
### Installation
1. Ensure you have [Yarn](https://yarnpkg.com/) installed
2. After cloning the repository, run `yarn install` in the root of the repository
3. To start a local development server serving the Docusaurus docs, go into the `website` directory and run `yarn start`
### Semantic commit messages
See how a minor change to your commit message style can make you a better programmer.
Format: `<type>(<scope>): <subject>`
`<scope>` is optional
**Example**
```
feat: allow overriding of webpack config
^--^ ^------------^
| |
| +-> Summary in present tense.
|
+-------> Type: chore, docs, feat, fix, refactor, style, or test.
```
The various types of commits:
- `feat`: (new feature for the user, not a new feature for build script)
- `fix`: (bug fix for the user, not a fix to a build script)
- `docs`: (changes to the documentation)
- `style`: (formatting, missing semi colons, etc; no production code change)
- `refactor`: (refactoring production code, eg. renaming a variable)
- `test`: (adding missing tests, refactoring tests; no production code change)
- `chore`: (updating grunt tasks etc; no production code change)
Use lower case not title case!
### Code conventions
#### Style guide
[Prettier](https://prettier.io/) will catch most styling issues that may exist in your code. You can check the status of your code styling by simply running `npm run prettier`.
However, there are still some styles that Prettier cannot pick up.
#### General
- **Most important: Look around.** Match the style you see used in the rest of the project. This includes formatting, naming files, naming things in code, naming things in documentation.
- "Attractive"
#### Documentation
- Do not wrap lines at 80 characters - configure your editor to soft-wrap when editing documentation.
## Pull requests
### Your first pull request
So you have decided to contribute code back to upstream by opening a pull request. You've invested a good chunk of time, and we appreciate it. We will do our best to work with you and get the PR looked at.
Working on your first Pull Request? You can learn how from this free video series:
[**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
We have a list of [beginner friendly issues](https://github.com/facebook/docusaurus/labels/good%20first%20issue) to help you get your feet wet in the Docusaurus codebase and familiar with our contribution process. This is a great place to get started.
### Proposing a change
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, you can also file an issue with [feature template](https://github.com/facebook/docusaurus/issues/new?template=feature.md/).
If you intend to change the public API (e.g., something in `docusaurus.config.js`), or make any non-trivial changes to the implementation, we recommend filing an issue with [proposal template](https://github.com/facebook/docusaurus/issues/new?template=proposal.md) and including `[Proposal]` in the title. This lets us reach an agreement on your proposal before you put significant effort into it. These types of issues should be rare.
If you're only fixing a bug, it's fine to submit a pull request right away but we still recommend to file an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
### Sending a pull request
Small pull requests are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it. It is recommended to follow this [commit message style](#semantic-commit-messages).
Please make sure the following is done when submitting a pull request:
1. Fork [the repository](https://github.com/facebook/docusaurus) and create your branch from `master`.
1. Add the copyright notice to the top of any code new files you've added.
1. Describe your [test plan](#test-plan) in your pull request description. Make sure to [test your changes](https://github.com/facebook/docusaurus/blob/master/admin/testing-changes-on-Docusaurus-itself.md/)!
1. Make sure your code lints (`yarn prettier && yarn lint`).
1. Make sure your Jest tests pass (`yarn test`).
1. If you haven't already, [sign the CLA](https://code.facebook.com/cla).
All pull requests should be opened against the `master` branch.
#### Test plan
A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI.
- If you've changed APIs, update the documentation.
#### Breaking changes
When adding a new breaking change, follow this template in your pull request:
```md
### New breaking change here
- **Who does this affect**:
- **How to migrate**:
- **Why make this breaking change**:
- **Severity (number of people affected x effort)**:
```
#### Copyright header for source code
Copy and paste this to the top of your new file(s):
```js
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
```
#### Contributor License Agreement (CLA)
In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, the Facebook GitHub Bot will reply with a link to the CLA form. You may also [complete your CLA here](https://code.facebook.com/cla).
### What happens next?
The core Docusaurus team will be monitoring for pull requests. Do help us by keeping pull requests consistent by following the guidelines above.
## License
By contributing to Docusaurus, you agree that your contributions will be licensed under its MIT license.

View file

@ -0,0 +1,93 @@
---
id: creating-pages
title: Creating Pages
---
In this section, we will learn about creating ad-hoc pages in Docusaurus using React. This is most useful for creating one-off standalone pages like a showcase page, playground page or support page.
The functionality of pages is powered by `@docusaurus/plugin-content-pages`.
## Adding a new page
<!-- TODO: What will the user see if pages/ is empty? -->
In the `/src/pages/` directory, create a file called `hello.js` with the following contents:
```jsx title="/src/pages/hello.js"
import React from 'react';
import Layout from '@theme/Layout';
function Hello() {
return (
<Layout title="Hello">
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '50vh',
fontSize: '20px',
}}>
<p>
Edit <code>pages/hello.js</code> and save to reload.
</p>
</div>
</Layout>
);
}
export default Hello;
```
Once you save the file, the development server will automatically reload the changes. Now open http://localhost:3000/hello, 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 a page in TypeScript, in which case the file name should use the `.tsx` extension, eg. `hello.tsx`.
:::
## 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`).
```sh
my-website
├── src
│ └── pages
│ ├── styles.module.css
│ ├── index.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. Do not put reusable components or test files (ending with `.test.js`) into that directory otherwise they will be turned into pages, which might not be intended.
:::
## Using React
React is used as the UI library to create pages. Every page component should export a React component and you can leverage on the expressiveness of React to build rich and interactive content.
<!--
TODO:
- That v2 is different from v1, users can write interactive components with lifecycles.
-->

View file

@ -0,0 +1,299 @@
---
id: deployment
title: 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.
You can deploy your site to static site hosting services such as [ZEIT Now](https://zeit.co/now), [GitHub Pages](https://pages.github.com/), [Netlify](https://www.netlify.com/), [Render](https://render.com/static-sites), and [Surge](https://surge.sh/help/getting-started-with-surge). Docusaurus sites are statically rendered so they work without JavaScript too!
## Deploying to GitHub Pages
Docusaurus provides an easy way to publish to [GitHub Pages](https://pages.github.com/). Which is hosting that comes for free with every GitHub repository.
### `docusaurus.config.js` settings
First, modify your `docusaurus.config.js` and add the required params:
| Name | Description |
| --- | --- |
| `organizationName` | The GitHub user or organization that owns the repository. If you are the owner, it is your GitHub username. In the case of Docusaurus, it is "_facebook_" which is the GitHub organization that owns Docusaurus. |
| `projectName` | The name of the GitHub repository. For example, the repository name for Docusaurus is "docusaurus", so the project name is "docusaurus". |
| `url` | URL for your GitHub Page's user/organization page. This is commonly https://_username_.github.io. |
| `baseUrl` | Base URL for your project. For projects hosted on GitHub pages, it follows the format "/_projectName_/". For https://github.com/facebook/docusaurus, `baseUrl` is `/docusaurus/`. |
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.
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.
Example:
```jsx {3-6} title="docusaurus.config.js"
module.exports = {
// ...
url: 'https://endiliey.github.io', // Your website URL
baseUrl: '/',
projectName: 'endiliey.github.io',
organizationName: 'endiliey',
// ...
};
```
:::tip
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
Specify the Git user as an environment variable.
| Name | Description |
| --- | --- |
| `GIT_USER` | The username for a GitHub account that has commit access to this repo. For your own repositories, this will usually be your GitHub username. The specified `GIT_USER` must have push access to the repository specified in the combination of `organizationName` and `projectName`. |
There are two more optional parameters that are set as environment variables:
| Name | Description |
| --- | --- |
| `USE_SSH` | Set to `true` to use SSH instead of the default HTTPS for the connection to the GitHub repo. |
| `DEPLOYMENT_BRANCH` | The branch that the website will be deployed to, defaults to `gh-pages` for normal repos and `master` for repository names ending in `github.io`. |
| `CURRENT_BRANCH` | The branch that contains the latest docs changes that will be deployed. Usually, the branch will be `master`, but it could be any branch (default or otherwise) except for `gh-pages`. If nothing is set for this variable, then the current branch will be used. |
### Deploy
Finally, to deploy your site to GitHub Pages, run:
**Bash**
```bash
GIT_USER=<GITHUB_USERNAME> yarn deploy
```
**Windows**
```batch
cmd /C "set "GIT_USER=<GITHUB_USERNAME>" && yarn deploy"
```
### 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.
This workflow assumes your documentation resided in `documentation` branch of your repository 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 `gh-pages` branch.
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).
1. By default, your public key should have been created in `~/.ssh/id_rsa.pub` or 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/).
1. Copy key to clipboard with `xclip -sel clip < ~/.ssh/id_rsa.pub` and paste it as a [deploy key](https://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys) in your repository. Copy file content if the command line doesn't work for you. Check the box for `Allow write access` before saving your deployment key.
1. 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.
1. Copy your private key with `xclip -sel clip < ~/.ssh/id_rsa` and paste a GitHub secret with name `GH_PAGES_DEPLOY`. Copy file content if the command line doesn't work for you. Save your secret.
1. Create you [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 `documentation.yml`.
```yaml title="documentation.yml"
name: documentation
on:
pull_request:
branches: [documentation]
push:
branches: [documentation]
jobs:
checks:
if: github.event_name != 'push'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: '12.x'
run: |
npm ci
npm run build
gh-release:
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: '12.x'
- name: Add key to allow access to repository
env:
SSH_AUTH_SOCK: /tmp/ssh_agent.sock
run: |
mkdir -p ~/.ssh
ssh-keyscan github.com >> ~/.ssh/known_hosts
echo "${{ secrets.GH_PAGES_DEPLOY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
cat <<EOT >> ~/.ssh/config
Host github.com
HostName github.com
IdentityFile ~/.ssh/id_rsa
EOT
- name: Release to GitHub Pages
env:
USE_SSH: true
GIT_USER: git
run: |
git config --global user.email "actions@gihub.com"
git config --global user.name "gh-actions"
npm ci
npx docusaurus deploy
```
1. Now when a new pull request arrives towards your repository in branch `documentation` it will automatically ensure that Docusaurus build is successful.
1. When pull request is merged to `documentation` branch or someone pushes to `documentation` branch directly it will be built and deployed to `gh-pages` branch.
1. After this step, your updated documentation will be available on the GitHub pages.
### 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/).
1. Using your GitHub account, [add the Travis CI app](https://github.com/marketplace/travis-ci) to the repository you want to activate.
1. 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.
1. 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).
1. Create a `.travis.yml` on the root of your repository with the following:
```yaml title=".travis.yml"
language: node_js
node_js:
- '10'
branches:
only:
- master
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 && GIT_USER="${GH_NAME}" yarn deploy
```
Now, whenever a new commit lands in `master`, Travis CI will run your suite of tests and if everything passes, your website will be deployed via the `yarn deploy` script.
## 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 {2-3} title="docusaurus.config.js"
module.exports = {
url: 'https://docusaurus-2.netlify.com', // Url to your site with no trailing slash
baseUrl: '/', // Base directory of your site relative to your repo
// ...
};
```
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`
- build directory: `build`
If you did not configure these build options, you may still go to "Site settings" -> "Build and 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 `master`.
:::important
Make sure to disable Netlify setting `Pretty URLs` to prevent lowercased URLs, unnecessary redirects and 404 errors.
:::
## Deploying to ZEIT Now
Deploying your Docusaurus project to [ZEIT Now](https://zeit.co/now) will provide you with [various benefits](https://zeit.co/now) in the areas of performance and ease of use.
Most importantly, however, deploying a Docusaurus project only takes a couple of seconds:
1. First, install their [command-line interface](https://zeit.co/download):
```bash
npm i -g now
```
1. Run a single command inside the root directory of your project:
```bash
now
```
**That's all.** Your docs will automatically be deployed.
Now you can connect your site to [GitHub](https://zeit.co/github) or [GitLab](https://zeit.co/gitlab) to automatically receive a new deployment every time you push a commit.
## Deploying to Render
Render 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. Deploy your app in just a few minutes by following these steps.
1. Create a new **Web Service** on Render, and give Render permission to access your Docusaurus repo.
1. Select the branch to deploy. The default is `master`.
1. Enter the following values during creation.
| Field | Value |
| --------------------- | ------------- |
| **Environment** | `Static Site` |
| **Build Command** | `yarn build` |
| **Publish Directory** | `build` |
That's it! Your app will be live on your Render URL as soon as the build finishes.
## 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
npm install --g surge
```
1. To build the static files of your site for production in the root directory of your project, run:
```bash
npm run build
```
1. 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(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
If you have a domain name you can deploy your site using surge to your domain using the command:
```bash
surge build/ yourdomain.com
```
Your site is now deployed for free at `subdomain.surge.sh` or `yourdomain.com` depending on the method you chose.
### 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`.

View file

@ -0,0 +1,34 @@
---
id: design-principles
title: Design Principles
---
:::caution
This section is a work in progress.
:::
- **Little to learn** - Docusaurus should be easy to learn and use as the API is quite small. Most things will still be achievable by users, even if it takes them more code and more time to write. Not having abstractions is better than having the wrong abstractions, and we don't want users to have to hack around the wrong abstractions. Mandatory talk - [Minimal API Surface Area](https://www.youtube.com/watch?v=4anAwXYqLG8).
- **Intuitive** - Users will not feel overwhelmed when looking at the project directory of a Docusaurus project or adding new features. It should look intuitive and easy to build on top of, using approaches they are familiar with.
- **Layered architecture** - The separations of concerns between each layer of our stack (content/theming/styling) should be clear - well-abstracted and modular.
- **Sensible defaults** - Common and popular performance optimizations and configurations will be done for users but they are given the option to override them.
- **No vendor-lock in** - Users are not required to use the default plugins or CSS, although they are highly encouraged to. Certain core lower-level infra level pieces like React Loadable, React Router cannot be swapped because we do default performance optimization on them. But not higher level ones, such as choice of Markdown engines, CSS frameworks, CSS methodology will be entirely up to users.
## How Docusaurus works
<!-- moved in from how Docusaurus works @yangshun -->
We believe that as developers, knowing how a library works is helpful in allowing us to become better at using it. Hence we're dedicating effort into explaining the architecture and various components of Docusaurus with the hope that users reading it will gain a deeper understanding of the tool and be even more proficient in using it.
<!--
Explain the principles that guide the development of Docusaurus.
References
---
- https://www.gatsbyjs.org/docs/behind-the-scenes/
- https://reactjs.org/docs/design-principles.html
- https://v1.vuepress.vuejs.org/miscellaneous/design-concepts.html
-->

View file

@ -0,0 +1,332 @@
---
id: docs-introduction
title: Docs Introduction
sidebar_label: Introduction
---
The docs feature provides users with a way to organize Markdown files in a hierarchical format.
## 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, `greeting.md` id is `greeting` and `guide/hello.md` id 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 user in the front matter. For example, if `guide/hello.md`'s content is defined as below, its final `id` is `guide/part1`.
```yml
---
id: part1
---
Lorem ipsum
```
## Home page docs
Using the `homePageId` property, you can create a home page of your docs. To do this, you can create a new document, especially for this purpose with the id as `_index`, or you could specify an existing document id.
```js {8} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
homePageId: 'getting-started', // Defaults to `_index`
// ...
},
},
],
],
// ...
};
```
Given the example above, now when you navigate to the path `/docs` you will see that the document content with id is `getting-started`. This functionality also works for docs with versioning enabled.
:::important
The document id of `_index` is reserved exclusively for the home doc page, so it will not work as a standalone route.
:::
:::note
The page `docs` that you created (eg. `src/pages/docs.js`) will take precedence over the route generated via the `homePageId` option.
:::
## Sidebar
To generate a sidebar to your Docusaurus site, you need to define a file that exports a sidebar object and pass that into the `@docusaurus/plugin-docs` plugin directly or via `@docusaurus/preset-classic`.
```js {8-9} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
// Sidebars filepath relative to the site dir.
sidebarPath: require.resolve('./sidebars.js'),
},
// ...
},
],
],
};
```
### Sidebar object
A sidebar object is defined like this:
```typescript
type Sidebar = {
[sidebarId: string]:
| {
[sidebarCategory: string]: SidebarItem[];
}
| SidebarItem[];
};
```
Below is an example of a sidebar object. The key `docs` is the id of the sidebar (can be renamed to something else) and `Getting Started` is a category within the sidebar. `greeting` and `doc1` are both [sidebar item](#sidebar-item).
```js title="sidebars.js"
module.exports = {
docs: {
'Getting started': ['greeting'],
Docusaurus: ['doc1'],
},
};
```
Keep in mind that EcmaScript does not guarantee `Object.keys({a,b}) === ['a','b']` (yet, this is generally true). If you don't want to rely on iteration order of JavaScript object keys for the category name, the following sidebar object is also equivalent of the above shorthand syntax.
```js title="sidebars.js"
module.exports = {
docs: [
{
type: 'category',
label: 'Getting Started',
items: ['greeting'],
},
{
type: 'category',
label: 'Docusaurus',
items: ['doc1'],
},
],
};
```
You can also have multiple sidebars for different Markdown files by adding more top-level keys to the exported object.
Example:
```js title="sidebars.js"
module.exports = {
firstSidebar: {
'Category A': ['doc1'],
},
secondSidebar: {
'Category A': ['doc2'],
'Category B': ['doc3'],
},
};
```
#### Sidebar item
As the name implies, `SidebarItem` is an item defined in a Sidebar. There are a few types we support:
- [Doc](#doc)
- [Link](#link)
- [Ref](#ref)
- [Category](#category)
#### Doc
```typescript
type SidebarItemDoc =
| string
| {
type: 'doc';
id: string;
};
```
Sidebar item type that links to a doc page. Example:
```js
{
type: 'doc',
id: 'doc1', // string - document id
}
```
Using just the [Document ID](#document-id) is perfectly valid as well, the following is equivalent to the above:
```js
'doc1'; // string - document id
```
Note that using this type will bind the linked doc to current sidebar, this means that if you access `doc1` page, the sidebar displayed will be the sidebar this item is on. For below case, `doc1` is bounded to `firstSidebar`.
```js title="sidebars.js"
module.exports = {
firstSidebar: {
'Category A': ['doc1'],
},
secondSidebar: {
'Category A': ['doc2'],
'Category B': ['doc3'],
},
};
```
#### Link
```typescript
type SidebarItemLink = {
type: 'link';
label: string;
href: string;
};
```
Sidebar item type that links to a non-document page. Example:
```js
{
type: 'link',
label: 'Custom Label', // The label that should be displayed (string).
href: 'https://example.com' // The target URL (string).
}
```
#### Ref
```typescript
type SidebarItemRef = {
type: 'ref';
id: string;
};
```
Sidebar item type that links to doc without bounding it to the sidebar. Example:
```js
{
type: 'ref',
id: 'doc1', // Document id (string).
}
```
#### Category
This is used to add hierarchies to the sidebar:
```typescript
type SidebarItemCategory = {
type: 'category';
label: string; // Sidebar label text.
items: SidebarItem[]; // Array of sidebar items.
};
```
As an example, here's how we created the subcategory for "Docs" under "Guides" in this site:
```js title="sidebars.js"
module.exports = {
docs: {
Guides: [
'creating-pages',
{
type: 'category',
label: 'Docs',
items: ['markdown-features', 'sidebar', 'versioning'],
},
],
},
};
```
**Note**: it's possible to use the shorthand syntax to create nested categories:
```js title="sidebars.js"
module.exports = {
docs: {
Guides: [
'creating-pages',
{
Docs: ['markdown-features', 'sidebar', 'versioning'],
},
],
},
};
```
#### Collapsible categories
For sites with a sizable amount of content, we support the option to expand/collapse a category to toggle the display of its contents. Categories are collapsible by default. If you want them to be always expanded, set `themeConfig.sidebarCollapsible` to `false`:
```js {4} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
sidebarCollapsible: false,
// ...
},
};
```
## Docs-only mode
If you just want the documentation feature, you can enable "docs-only mode".
To achieve this, set the `routeBasePath` property of the `docs` object in `@docusaurus/preset-classic` in `docusaurus.config.js` to the root of your site, and also in that object set the `homePageId` property with the value of the document ID that you show as root of the docs.
:::note
More details on functionality of home page for docs can be found in [appropriate section](#home-page-docs).
:::
```js {8-9} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
routeBasePath: '/', // Set this value to '/'.
homePageId: 'getting-started', // Set to existing document id.
// ...
},
},
],
],
// ...
};
```
Now, when visiting your site, it will show your initial document instead of a landing page.
:::tip
There's also a "blog-only mode", for those who only want to use the blog component of Docusaurus 2. You can use the same method detailed above, except that you need to delete the `/src/pages/index.js` file. Follow the setup instructions on [Blog-only mode](blog.md#blog-only-mode).
:::

View file

@ -0,0 +1,197 @@
---
id: docusaurus-core
title: Docusaurus Client API
sidebar_label: Client API
---
Docusaurus provides some APIs on the clients that can be helpful to you when building your site.
## Components
### `<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 {2,6,11}
import React from 'react';
import Head from '@docusaurus/Head';
const MySEO = () => (
<>
<Head>
<meta property="og:description" content="My custom description" />
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://mysite.com/example" />
</Head>
</>
);
```
Nested or latter components will override duplicate usages:
```jsx {2,5,8,11}
<Parent>
<Head>
<title>My Title</title>
<meta name="description" content="Helmet application" />
</Head>
<Child>
<Head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</Head>
</Child>
</Parent>
```
Outputs
```html
<head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</head>
```
### `<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 `<Link>` 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-routers `<Link>` component that adds useful enhancements specific to Docusaurus. All props are passed through to react-routers `<Link>` component.
```jsx {2,7}
import React from 'react';
import Link from '@docusaurus/Link';
const Page = () => (
<div>
<p>
Check out my <Link to="/blog">blog</Link>!
</p>
<p>
{/* Note that external links still use `a` tags, but automatically opens in new tab. */}
Follow me on <a href="https://twitter.com/docusaurus">Twitter</a>!
</p>
</div>
);
```
#### `to`: string
The target location to navigate to. Example: `/docs/introduction`.
```jsx
<Link to="/courses" />
```
### `<Redirect/>`
Rendering a `<Redirect>` 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 {2,5}
import React from 'react';
import {Redirect} from '@docusaurus/router';
function Home() {
return <Redirect to="/docs/test" />;
}
```
### `<BrowserOnly/>`
The `<BrowserOnly>` component accepts a `children` prop, a render function which will not be executed during the pre-rendering phase of the build process. This is useful for hiding code that is only meant to run in the browsers (e.g. where the `window`/`document` objects are being accessed). To improve SEO, you can also provide fallback content using the `fallback` prop, which will be prerendered until in the build process and replaced with the client-side only contents when viewed in the browser.
```jsx
import BrowserOnly from '@docusaurus/BrowserOnly';
function MyComponent() {
return (
<BrowserOnly
fallback={<div>The fallback content to display on prerendering</div>}>
{() => {
// Something that should be excluded during build process prerendering.
}}
</BrowserOnly>
);
}
```
## Hooks
### `useDocusaurusContext`
React hook to access Docusaurus Context. Context contains `siteConfig` object from [docusaurus.config.js](docusaurus.config.js.md).
```ts
interface DocusaurusContext {
siteConfig?: DocusaurusConfig;
}
```
Usage example:
```jsx {2,5}
import React from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
const Test = () => {
const context = useDocusaurusContext();
const {siteConfig = {}} = context;
const {title} = siteConfig;
return <h1>{title}</h1>;
};
```
### `useBaseUrl`
React hook to automatically prepend `baseUrl` to a string automatically. This is particularly useful if you don't want to hardcode your config's `baseUrl`. We highly recommend you to use this.
Example usage:
```jsx {3,11}
import React, {useEffect} from 'react';
import Link from '@docusaurus/Link';
import useBaseUrl from '@docusaurus/useBaseUrl';
function Help() {
return (
<div className="col">
<h2>Browse the docs</h2>
<p>
Learn more about Docusaurus using the{' '}
<Link to={useBaseUrl('docs/introduction')}>official documentation</Link>
</p>
</div>
);
}
```
## Modules
### `ExecutionEnvironment`
A module which exposes a few boolean variables to check the current rendering environment. Useful if you want to only run certain code on client/server or need to write server-side rendering compatible code.
```jsx {2}
import React from 'react';
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
function MyPage() {
const location = ExecutionEnvironment.canUseDOM ? window.href.location : null;
return <div>{location}</div>;
}
```
| Field | Description |
| --- | --- |
| `ExecutionEnvironment.canUseDOM` | `true` if on client, `false` if 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`. |

View file

@ -0,0 +1,289 @@
---
id: docusaurus.config.js
title: docusaurus.config.js
description: API reference for Docusaurus configuration file.
---
## Overview
`docusaurus.config.js` contains configurations for your site and is placed in the root directory of your site.
## Required fields
### `title`
- Type: `string`
Title for your website.
```js title="docusaurus.config.js"
module.exports = {
title: 'Docusaurus',
};
```
### `favicon`
- Type: `string`
URL for site favicon. Example:
```js title="docusaurus.config.js"
module.exports = {
favicon: 'https://v2.docusaurus.io/favicon.ico',
};
```
You can also use the favicon URL relative to the `static` directory of your site. For example, your site has the following directory structure:
```bash
.
├── README.md
├ # ... other files in root directory
└─ static
└── img
└── favicon.ico
```
So you can refer it like below:
```js title="docusaurus.config.js"
module.exports = {
favicon: 'img/favicon.ico',
};
```
### `url`
- Type: `string`
URL for your website. This can also be considered the top-level hostname. For example, `https://facebook.github.io` is the URL of https://facebook.github.io/metro/, and `https://docusaurus.io` is the URL for https://docusaurus.io. This field is related to the [baseUrl](#baseurl) field.
```js title="docusaurus.config.js"
module.exports = {
url: 'https://docusaurus.io',
};
```
### `baseUrl`
- Type: `string`
Base URL for your site. This can also be considered the path after the host. For example, `/metro/` is the baseUrl of https://facebook.github.io/metro/. For URLs that have no path, the baseUrl should be set to `/`. This field is related to the [url](#url) field.
```js title="docusaurus.config.js"
module.exports = {
baseUrl: '/',
};
```
## Optional fields
### `tagline`
- Type: `string`
The tagline for your website.
```js title="docusaurus.config.js"
module.exports = {
tagline:
'Docusaurus makes it easy to maintain Open Source documentation websites.',
};
```
### `organizationName`
- Type: `string`
The GitHub user or organization that owns the repository. Used by the deployment command.
```js title="docusaurus.config.js"
module.exports = {
// Docusaurus' organization is facebook
organizationName: 'facebook',
};
```
### `projectName`
- Type: `string`
The name of the GitHub repository. Used by the deployment command.
```js title="docusaurus.config.js"
module.exports = {
projectName: 'docusaurus',
};
```
### `githubHost`
- Type: `string`
The hostname of your server. Useful if you are using GitHub Enterprise.
```js title="docusaurus.config.js"
module.exports = {
githubHost: 'github.com',
};
```
### `themeConfig`
- Type: `Object`
<!-- TODO: explain that theme configurations will be consumed by the theme, and link to theme doc -->
An object containing data needed by the theme you use.<!--, see [theme configurations](#).-->
For Docusaurus' default theme _classic_, we use `themeConfig` to customize your navbar and footer links:
Example:
```js title="docusaurus.config.js"
module.exports = {
themeConfig: {
navbar: {
title: 'Site Title',
logo: {
alt: 'Site Logo',
src: 'img/logo.svg',
},
links: [
{
to: 'docs/docusaurus.config.js',
activeBasePath: 'docs',
label: 'docusaurus.config.js',
position: 'left',
},
// ... other links
],
},
footer: {
style: 'dark',
links: [
{
title: 'Docs',
items: [
{
label: 'Docs',
to: 'docs/doc1',
},
],
},
// ... other links
],
logo: {
alt: 'Facebook Open Source Logo',
src: 'https://docusaurus.io/img/oss_logo.png',
},
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`, // You can also put own HTML here
},
},
};
```
### `plugins`
<!-- TODO: configuration for plugins -->
- Type: `any[]`
```js title="docusaurus.config.js"
module.exports = {
plugins: [],
};
```
### `themes`
<!-- TODO: configuration for plugins -->
- Type: `any[]`
```js title="docusaurus.config.js"
module.exports = {
themes: [],
};
```
### `presets`
<!-- TODO: configuration for presets -->
- Type: `any[]`
```js title="docusaurus.config.js"
module.exports = {
presets: [],
};
```
### `customFields`
Docusaurus guards `docusaurus.config.js` from unknown fields. To add a custom field, define it on `customFields`.
- Type: `Object`
```js title="docusaurus.config.js"
module.exports = {
customFields: {
admin: 'endi',
superman: 'lol',
},
};
```
Attempting to add unknown field in the config will lead to error in build time:
```bash
Error: The field(s) 'foo', 'bar' are not recognized in docusaurus.config.js
```
### `scripts`
An array of scripts to load. The values can be either strings or plain objects of attribute-value maps. The `<script>` tags will be inserted in the HTML `<head>`.
Note that `<script>` added here are render-blocking so you might want to add `async: true`/`defer: true` to the objects.
- Type: `(string | Object)[]`
Example:
```js title="docusaurus.config.js"
module.exports = {
scripts: [
// String format.
'https://docusaurus.io/script.js',
// Object format.
{
src:
'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
async: true,
},
],
};
```
### `stylesheets`
An array of CSS sources to load. The values can be either strings or plain objects of attribute-value maps. The `<link>` tags will be inserted in the HTML `<head>`.
- Type: `(string | Object)[]`
Example:
```js title="docusaurus.config.js"
module.exports = {
stylesheets: [
// String format.
'https://docusaurus.io/style.css',
// Object format.
{
href: 'http://mydomain.com/style.css',
type: 'text/css',
},
],
};
```

View file

@ -0,0 +1,139 @@
---
id: installation
title: Installation
---
Docusaurus is essentially a set of npm [packages](https://github.com/facebook/docusaurus/tree/master/packages) that can be installed over npm.
## Requirements
- [Node.js](https://nodejs.org/en/download/) version >= 10.15.1 or above (which can be checked by running `node -v`). You can use [nvm](https://github.com/nvm-sh/nvm) for managing multiple Node versions on a single machine installed
- [Yarn](https://yarnpkg.com/en/) version >= 1.5 (which can be checked by running `yarn version`). Yarn is a performant package manager for JavaScript and replaces the `npm` client. It is not strictly necessary but highly encouraged.
## Scaffold project website
The easiest way to install Docusaurus is to use the command line tool that helps you scaffold a skeleton Docusaurus website. You can run this command anywhere in a new empty repository or within an existing repository, it will create a new directory containing the scaffolded files.
```bash
npx @docusaurus/init@next init [name] [template]
```
Example:
```bash
npx @docusaurus/init@next init my-website classic
```
If you do not specify `name` or `template`, it will prompt you for them. We recommend the `classic` template so that you can get started quickly and it contains features found in Docusaurus 1. The `classic` template contains `@docusaurus/preset-classic` which includes standard documentation, a blog, custom pages, and a CSS framework (with dark mode support). You can get up and running extremely quickly with the classic template and customize things later on when you have gained more familiarity with Docusaurus.
**[FB-Only]:** If you are setting up a new Docusaurus website for a Facebook open source project, use the `facebook` template instead, which comes with some useful Facebook-specific defaults:
```bash
npx @docusaurus/init@next init my-website facebook
```
## Project structure
Assuming you chose the classic template and named your site `my-website`, you will see the following files generated under a new directory `my-website/`:
```sh
my-website
├── blog
│ ├── 2019-05-28-hola.md
│ ├── 2019-05-29-hello-world.md
│ └── 2020-05-30-welcome.md
├── docs
│ ├── doc1.md
│ ├── doc2.md
│ ├── doc3.md
│ └── mdx.md
├── src
│ ├── css
│ │ └── custom.css
│ └── pages
│ ├── styles.module.css
│ └── index.js
├── static
│ └── img
├── docusaurus.config.js
├── package.json
├── README.md
├── sidebars.js
└── yarn.lock
```
### Project structure rundown
- `/blog/` - Contains the blog Markdown files. You can delete the directory if you do not want/need a blog. More details can be found in the [blog guide](blog.md).
- `/docs/` - Contains the Markdown files for the docs. Customize the order of the docs sidebar in `sidebars.js`. More details can be found in the [docs guide](markdown-features.mdx).
- `/src/` - Non-documentation files like pages or custom React components. You don't have to strictly put your non-documentation files in here but putting them under a centralized directory makes it easier to specify in case you need to do some sort of linting/processing
- `/src/pages` - Any files within this directory will be converted into a website page. More details can be found in the [pages guide](creating-pages.md).
- `/static/` - Static directory. Any contents inside here will be copied into the root of the final `build` directory.
- `/docusaurus.config.js` - A config file containing the site configuration. This is the equivalent of `siteConfig.js` in Docusaurus 1.
- `/package.json` - A Docusaurus website is a React app. You can install and use any npm packages you like in them.
- `/sidebar.js` - Used by the documentation to specify the order of documents in the sidebar.
## Running the development server
To preview your changes as you edit the files, you can run a local development server that will serve your website and it will reflect the latest changes.
```bash npm2yarn
cd my-website
npm run start
```
By default, a browser window will open at http://localhost:3000.
Congratulations! You have just created your first Docusaurus site! Browse around the site to see what's available.
## Build
Docusaurus is a modern static website generator so we need to build the website into a directory of static contents and put it on a web server so that it can be viewed. To build the website:
```bash npm2yarn
npm run build
```
and contents will be generated within the `/build` directory, which can be copied to any static file hosting service like [GitHub pages](https://pages.github.com/), [Now](https://zeit.co/now) or [Netlify](https://www.netlify.com/). Check out the docs on [deployment](deployment.md) for more details.
## Updating your Docusaurus version
There are many ways to update your Docusaurus version. One guaranteed way is to manually change the version number in `package.json` to the desired version. Note that all `@docusaurus/`-namespaced packages should be using the same version.
:::important
Please update to the latest Docusaurus 2 version shown at the top of the page, not what is shown below.
:::
```json title="package.json"
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.49",
"@docusaurus/preset-classic": "^2.0.0-alpha.49",
// ...
}
```
Then, in the directory containing `package.json`, run your package manager's install command:
```bash npm2yarn
npm install
```
To check that that the update occurred successfully, run:
```bash npm2yarn
npm docusaurus --version
```
You should see the correct version as output.
Alternatively, if you are using Yarn, you can do:
```bash
yarn upgrade @docusaurus/core@2.0.0-alpha.49 @docusaurus/preset-classic@2.0.0-alpha.49
```
## Problems?
Ask for help on [Stack Overflow](https://stackoverflow.com/questions/tagged/docusaurus), on our [GitHub repository](https://github.com/facebook/docusaurus) or [Twitter](https://twitter.com/docusaurus).

View file

@ -0,0 +1,113 @@
---
id: introduction
title: Introduction
description: Docusaurus was designed from the ground up to be easily installed and used to get your website up and running quickly.
---
## Disclaimer
It has been a year since we made the first **alpha release** of Docusaurus 2 and things have been pretty stable since then. Many of Facebook's new open source websites are using Docusaurus 2 now. At this point, we highly encourage you to use Docusaurus 2 over Docusaurus 1 for your new websites. For feedback and questions, chat with us on [**Discord**](https://discordapp.com/invite/docusaurus) :wink:
**You should use this if:**
- :white_check_mark: You want to contribute to Docusaurus 2
- :white_check_mark: You want to build a modern website with client-side routing and prerendering
- :white_check_mark: You want to provide feedback to make sure Docusaurus 2 suits your needs
- :white_check_mark: You are curious about what comes next as a Docusaurus user
- :white_check_mark: You want to ease the pain of migration in future
- :white_check_mark: You do not need support for IE11
**Do not use this if:**
- :x: You need a fully production-ready solution (try [Docusaurus 1](https://docusaurus.io/) instead)
- :x: You need the translation features present in v1
- :x: You prefer not to work with potential breaking changes and/or features not yet working properly as we improve it during the alpha period
- :x: You need support for IE11
## A better Docusaurus is coming to town
<img alt="Docusaurus " src={require('@docusaurus/useBaseUrl').default('img/slash-introducing.svg')} />
Docusaurus 1 used to be a pure documentation site generator. In Docusaurus 2, we rebuilt it from the ground up, allowing for more customizability but preserved the best parts of Docusaurus 1 - easy to get started, versioned docs, and i18n (_coming soon_).
Beyond that, Docusaurus 2 is a **performant static site generator** and can be used to create common content-driven websites (e.g. Documentation, Blogs, Product Landing and Marketing Pages, etc) extremely quickly.
While our main focus will still be helping you get your documentations right and well, it is possible to build this any kind of website using Docusaurus 2 as it is just a React application. **Docusaurus can now be used to build any website, not just documentation websites.**
## Features
Docusaurus is built with high attention to your experience building your site and maintaining it with your collaborators and contributors.
- ⚛️ **Built with 💚 and React**
- Extend and customize with React
- Gain full control of your site's browsing experience by `swizzling` in your own components
- **Pluggable**
- Bootstrap your site with a basic template, then pick and plug functionalities built by us and our community
- Open source your plugins to share with your fellow documentarians, because sharing is caring
- ✂️ **Developer experience**
- Multiple bootstrapping templates to get your site up and running, start writing your docs right now
- Universal configuration entry point to make it more maintainable by contributors
- Hot reloading with lightning fast incremental build on changes
- Route-based code and data splitting
- Publish to GitHub Pages, Netlify, and other deployment services with ease
Our shared goal — to help your users find what they need fast, and understand your products better. With the experience of Docusaurus 1, we share with you our best practices to help you build your doc site right and well.
- 🎯 **SEO friendly**
- HTML files are statically generated for every possible path
- page-specific SEO to help your users land on your official docs directly relating their problems at hand
- 📝 **Powered by MDX**
- Write interactive components via JSX and React embedded in markdown
- Share your code in live editors to get your users love your products on the spot
- 🔍 **Search** - Your full site is searchable
- 💾 **Document Versioning** - Helps you keep documentation in sync with project releases.
- 🌍 **i18n** (_coming soon_)
Docusaurus 2 is born to be compassionately accessible to all your users, and lightning fast.
- ⚡️ **Lightning fast** - Docusaurus 2 follows the [PRPL Pattern](https://developers.google.com/web/fundamentals/performance/prpl-pattern/) that makes sure your content loads blazing fast
- 🦖 **Accessible** - Attention to accessibility, making your site equally accessible to all users
## Comparison with other tools
Across all static site generators, Docusaurus has a unique focus on doc sites and has out-of-the-box structure you need.
We've also studied other main static site generators and would like to share our insights on the comparison, hopefully to help you navigate through the prismatic choices out there.
### Gatsby
Gatsby is packed with a lot of features, has a rich ecosystem of plugins and is capable of doing everything that Docusaurus does. Naturally, that comes at a cost of a higher learning curve. Gatsby does many things well and is suitable for building many types of websites. On the other hand, Docusaurus tries to do one thing super well - be the best tool for writing and publishing content.
GraphQL is also pretty core to Gatsby, although you don't necessarily need GraphQL to build a Gatsby site. In most cases when building static websites, you won't need the flexibility that GraphQL provides.
Many aspects of Docusaurus 2 were inspired by the best things about Gatsby and it's a great alternative.
### GitBook
GitBook has very clean design and has been used by many open source projects. With its focus shifting towards a commercial product rather than an open-source tool, many of its requirements no longer fit the needs as an open source project's documentation site. As a result, many have turned to other products. You may read about Redux's switch to Docusaurus [here](https://github.com/reduxjs/redux/issues/3161).
Currently, GitBook is only free for open-source and non-profit teams. Docusaurus is free for everyone.
### Jekyll
Jekyll is one of the most mature static site generators around and has been a great tool to use — in fact, before Docusaurus, most of Facebook's Open Source websites are/were built on Jekyll! It is extremely simple to get started. We want to bring a similar developer experience as building a static site with Jekyll.
In comparison with statically generated HTML and interactivity added using `<script />` tags, Docusaurus sites are React apps. Using modern JavaScript ecosystem tooling, we hope to set new standards on doc sites performance, asset build pipeline and optimizations, and ease to setup.
### VuePress
VuePress has many similarities with Docusaurus - both focus heavily on content-centric website and provides tailored documentation features out of the box. However, VuePress is powered by Vue, while Docusaurus is powered by React. If you want a Vue-based solution, VuePress would be a decent choice.
<!-- TODO: Add a Next.js comparison -->
## Staying informed
- [GitHub](https://github.com/facebook/docusaurus)
- [Twitter](https://twitter.com/docusaurus)
- [Blog](/blog)
## Something missing?
If you find issues with the documentation or have suggestions on how to improve the documentation or the project in general, please [file an issue](https://github.com/facebook/docusaurus) for us, or send a tweet mentioning the [@docusaurus](https://twitter.com/docusaurus) Twitter account.
For new feature requests, you can create a post on our [Canny board](/feedback), which is a handy tool for roadmapping and allows for sorting by upvotes, which gives the core team a better indicator of what features are in high demand, as compared to GitHub issues which are harder to triage. Refrain from making a Pull Request for new features (especially large ones) as someone might already be working on it or will be part of our roadmap. Talk to us first!

View file

@ -0,0 +1,434 @@
---
id: lifecycle-apis
title: Lifecycle APIs
---
:::caution
This section is a work in progress.
:::
Lifecycle APIs are shared by Themes and Plugins.
## `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.
Example:
```js {5-7} title="docusaurus-plugin/src/index.js"
const path = require('path');
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
getPathsToWatch() {
const contentPath = path.resolve(context.siteDir, options.path);
return [`${contentPath}/**/*.{ts,tsx}`];
},
};
};
```
## `async loadContent()`
Plugins should use this lifecycle to fetch from data sources (filesystem, remote API, headless CMS, etc) or doing some server processing.
For example, this plugin below return a random integer between 1 to 10 as content;
```js {5-6} title="docusaurus-plugin/src/index.js"
const path = require('path');
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
async loadContent() {
return 1 + Math.floor(Math.random() * 10);
},
};
};
```
## `async contentLoaded({content, actions})`
Plugins should use the data loaded in `loadContent` and construct the pages/routes that consume the loaded data (optional).
## `async routesLoaded(routes)`
Plugins can modify the routes that were generated by all plugins. `routesLoaded` is called after `contentLoaded` hook.
### `content`
`contentLoaded` will be called _after_ `loadContent` is done, the return value of `loadContent()` will be passed to `contentLoaded` as `content`.
### `actions`
`actions` contain two functions:
- `addRoute(config: RouteConfig): void`
Create a route to add to the website.
```typescript
interface RouteConfig {
path: string;
component: string;
modules?: RouteModule;
routes?: RouteConfig[];
exact?: boolean;
priority?: number;
}
interface RouteModule {
[module: string]: Module | RouteModule | RouteModule[];
}
type Module =
| {
path: string;
__import?: boolean;
query?: ParsedUrlQueryInput;
}
| string;
```
- `createData(name: string, data: any): Promise<string>`
A helper function to help you write some data (usually a string or JSON) to disk with in-built caching. It takes a file name relative to to your plugin's directory **(name)**, your data **(data)**, and will return a path to where the data is created.
For example, this plugin below create a `/roll` page which display "You won xxxx" to user.
```jsx title="website/src/components/roll.js"
import React from 'react';
export default function (props) {
const {prizes} = props;
const index = Math.floor(Math.random() * 3);
return <div> You won ${prizes[index]} </div>;
}
```
```javascript {4-19} title="docusaurus-plugin/src/index.js"
module.exports = function(context, options) {
return {
name: 'docusaurus-plugin',
async contentLoaded({content, actions}) {
const {createData, addRoute} = actions;
// Create a data named 'prizes.json'.
const prizes = JSON.stringify(['$1', 'a cybertruck', 'nothing']);
const prizesDataPath = await createData('prizes.json', prizes);
// Add '/roll' page using 'website/src/component/roll.js` as the component
// and providing 'prizes' as props.
addRoute({
path: '/roll',
component: '@site/src/components/roll.js',
modules: {
prizes: prizesDataPath
}
exact: true,
});
},
};
};
```
## `configureWebpack(config, isServer, utils)`
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 argument argument.
### `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`
`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`
The initial call to `configureWebpack` also receives a util object consists of three functions:
- `getStyleLoaders(isServer: boolean, cssOptions: {[key: string]: any}): Loader[]`
- `getCacheLoader(isServer: boolean, cacheOptions?: {}): Loader | null`
- `getBabelLoader(isServer: boolean, babelOptions?: {}): Loader`
You may use them to return your webpack configures conditionally.
For example, this plugin below modify the webpack config to transpile `.foo` file.
```js {4-11} title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'custom-docusaurus-plugin',
configureWebpack(config, isServer, utils) {
const {getCacheLoader} = utils;
return {
module: {
rules: [
{
test: /\.foo$/,
use: [getCacheLoader(isServer), 'my-custom-webpack-loader'],
},
],
},
};
},
};
};
```
## `postBuild(props)`
Called when a (production) build finishes.
```ts
type Props = {
siteDir: string;
generatedFilesDir: string;
siteConfig: DocusaurusConfig;
outDir: string;
baseUrl: string;
headTags: string;
preBodyTags: string;
postBodyTags: string;
routesPaths: string[];
plugins: Plugin<any>[];
};
```
Example:
```js {4-9} title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
async postBuild({siteConfig = {}, routesPaths = [], outDir}) {
// Print out to console all the rendered routes.
routesPaths.map((route) => {
console.log(route);
});
},
};
};
```
## `extendCli(cli)`
Register an extra command to enhance the CLI of docusaurus. `cli` is [commander](https://www.npmjs.com/package/commander) object.
Example:
```js {4-11} title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
extendCli(cli) {
cli
.command('roll')
.description('Roll a random number between 1 and 1000')
.action(() => {
console.log(Math.floor(Math.random() * 1000 + 1));
});
},
};
};
```
## `injectHtmlTags()`
Inject head and/or body HTML tags to Docusaurus generated HTML.
```typescript
function injectHtmlTags(): {
headTags?: HtmlTags;
preBodyTags?: HtmlTags;
postBodyTags?: HtmlTags;
};
type HtmlTags = string | HtmlTagObject | (string | HtmlTagObject)[];
interface 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 {4-28} title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
injectHtmlTags() {
return {
headTags: [
{
tagName: 'link',
attributes: {
rel: 'preconnect',
href: 'https://www.github.com',
},
},
],
preBodyTags: [
{
tagName: 'script',
attributes: {
charset: 'utf-8',
src: '/noflash.js',
},
},
],
postBodyTags: [`<div> This is post body </div>`],
};
},
};
};
```
## `getThemePath()`
Returns the path to the directory where the theme components can be found. When your users calls `swizzle`, `getThemePath` is called and its returned path is used to find your theme components.
If you use the folder directory above, your `getThemePath` can be:
```js {6-8} title="my-theme/src/index.js"
const path = require('path');
module.exports = function (context, options) {
return {
name: 'name-of-my-theme',
getThemePath() {
return path.resolve(__dirname, './theme');
},
};
};
```
## `getClientModules()`
Returns 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.
As an example, to make your theme load a `customCss` object from `options` passed in by the user:
```js {7-9} title="my-theme/src/index.js"
const path = require('path');
module.exports = function (context, options) {
const {customCss} = options || {};
return {
name: 'name-of-my-theme',
getClientModules() {
return [customCss];
},
};
};
```
<!--
For example, the in docusaurus-plugin-content-docs:
In loadContent, it loads the doc Markdown files based on the specified directory in options (defaulting to docs).
In contentLoaded, for each doc Markdown file, a route is created: /doc/installation, /doc/getting-started, etc.
-->
## Example
Here's a mind model for a presumptuous plugin implementation.
```jsx
const DEFAULT_OPTIONS = {
// Some defaults.
};
// 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.
module.exports = function (context, opts) {
// Merge defaults with user-defined options.
const options = {...DEFAULT_OPTIONS, ...options};
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 routesLoaded(routes) {
// The routesLoaded hook is done after contentLoaded hook is done.
// This can be useful if you need to change any route.
},
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) {
// 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() {
// Inject head and/or body HTML tags.
},
};
};
```

View file

@ -0,0 +1,829 @@
---
id: markdown-features
title: Markdown Features
description: Docusaurus uses GitHub Flavored Markdown (GFM). Find out more about Docusaurus-specific features when writing Markdown.
---
Documentation is one of your product's interfaces with your users. A well-written and well-organized set of docs helps your users understand your product quickly. Our aligned goal here is to help your users find and understand the information they need, as quickly as possible.
Docusaurus 2 uses modern tooling to help you compose your interactive documentations with ease. You may embed React components, or build live coding blocks where your users may play with the code on the spot. Start sharing your eureka moments with the code your audience cannot walk away from. It is perhaps the most effective way of attracting potential users.
In this section, we'd like to introduce you to the tools we've picked that we believe will help you build powerful documentation. Let us walk you through with an example.
:::important
All the following content assumes you are using `@docusaurus/preset-classic` or `@docusaurus/plugin-content-docs`.
:::
---
Markdown is a syntax that enables you to write formatted content in a readable syntax. The [standard Markdown syntax](https://daringfireball.net/projects/markdown/syntax) is supported and we use [MDX](https://mdxjs.com/) as the parsing engine, which can do much more than just parsing Markdown. More on that later.
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
├── ...
```
<!-- TODO: talk about where to put the docs, resolving docs outside of website directory, etc. -->
At the top of the file, specify `id` and `title` in the front matter, so that Docusaurus will pick them up correctly when generating your site.
```yml
---
id: greeting
title: Hello
---
## 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
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
```
This will render in the browser as follows:
import BrowserWindow from '@site/src/components/BrowserWindow';
<BrowserWindow url="http://localhost:3000">
<h2>Hello from Docusaurus</h2>
Are you ready to create the documentation site for your open source project?
<h3>Headers</h3>
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.
<h3>Only h2 and h3 will be in the toc</h3>
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
</BrowserWindow>
## Markdown headers
Documents use the following markdown header fields that are enclosed by a line `---` on either side:
- `id`: A unique document id. If this field is not present, the document's `id` will default to its file name (without the extension).
- `title`: The title of your document. If this field is not present, the document's `title` will default to its `id`.
- `hide_title`: Whether to hide the title at the top of the doc. By default it is `false`.
- `hide_table_of_contents`: Whether to hide the table of contents to the right. By default it is `false`.
- `sidebar_label`: The text shown in the document sidebar and in the next/previous button for this document. If this field is not present, the document's `sidebar_label` will default to its `title`.
- `custom_edit_url`: The URL for editing this document. If this field is not present, the document's edit URL will fall back to `editUrl` from options fields passed to `docusaurus-plugin-content-docs`.
- `keywords`: Keywords meta tag for the document page, for search engines.
- `description`: 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. If this field is not present, it will default to the first line of the contents.
- `image`: Cover or thumbnail image that will be used when displaying the link to your post.
Example:
```yml
---
id: doc-markdown
title: Markdown Features
hide_title: false
hide_table_of_contents: false
sidebar_label: Markdown :)
custom_edit_url: https://github.com/facebook/docusaurus/edit/master/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
---
```
## Referencing other documents
If you want to reference another document file, you could use the name of the document you want to reference. Docusaurus will convert the file path to be the final website path (and remove the `.md`).
For example, if you are in `doc2.md` and you want to reference `doc1.md` and `folder/doc3.md`:
```md
I am referencing a [document](doc1.md). Reference to another [document in a folder](folder/doc3.md).
[Relative document](../doc2.md) referencing works as well.
```
One benefit of this approach is that the links to external files will still work if you are viewing the file on GitHub.
## Embedding React components with MDX
Docusaurus has built-in support for [MDX](https://mdxjs.com/), which allows you to write JSX within your Markdown files and render them as React components.
**Note 1:** While both `.md` and `.mdx` files are parsed using MDX, some of the syntax are treated slightly differently. For the most accurate parsing and better editor support, we recommend using the `.mdx` extension for files containing MDX syntax. Let's rename the previous file to `greeting.mdx`.
**Note 2:** Since all doc files are parsed using MDX, any HTML is treated as JSX. Therefore, if you need to inline-style a component, follow JSX flavor and provide style objects. This behavior is different from Docusaurus 1. See also [Migrating from v1 to v2](migrating-from-v1-to-v2.md#convert-style-attributes-to-style-objects-in-mdx).
Try this block here:
```jsx
export const Highlight = ({children, color}) => (
<span
style={{
backgroundColor: color,
borderRadius: '2px',
color: '#fff',
padding: '0.2rem',
}}>
{children}
</span>
);
<Highlight color="#25c2a0">Docusaurus green</Highlight> and <Highlight color="#1877F2">Facebook blue</Highlight> are my favorite colors.
I can write **Markdown** alongside my _JSX_!
```
Notice how it renders both the markup from your React component and the Markdown syntax:
export const Highlight = ({children, color}) => (
<span
style={{
backgroundColor: color,
borderRadius: '2px',
color: '#fff',
padding: '0.2rem',
}}>
{children}
</span>
);
<BrowserWindow minHeight={240} url="http://localhost:3000">
<Highlight color="#25c2a0">Docusaurus green</Highlight>
{` `}and <Highlight color="#1877F2">Facebook blue</Highlight> are my favorite colors.
I can write **Markdown** alongside my _JSX_!
</BrowserWindow>
<br />
You can also import your own components defined in other files or third-party components installed via npm! Check out the [MDX docs](https://mdxjs.com/) to see what other fancy stuff you can do with MDX.
### Configuring plugins
You can expand the MDX functionalities, using plugins. An MDX plugin is usually a npm package, so you install them like other npm packages using npm. Docusaurus supports both [Remark](https://github.com/remarkjs/remark) and [Rehype](https://github.com/rehypejs/rehype) plugins that work with MDX.
First, install your [Remark](https://github.com/remarkjs/remark/blob/master/doc/plugins.md#list-of-plugins) and [Rehype](https://github.com/rehypejs/rehype/blob/master/doc/plugins.md#list-of-plugins) plugins.
For example:
```bash npm2yarn
npm install --save remark-images
npm install --save rehype-truncate
```
Next, import the plugins:
```js
const remarkImages = require('remark-images');
const rehypeTruncate = require('rehype-truncate');
```
Finally, add them to the `@docusaurus/preset-classic` options in `docusaurus.config.js`:
```js {10,11} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.js'),
// ...
remarkPlugins: [remarkImages],
rehypePlugins: [rehypeTruncate],
},
},
],
],
};
```
### Configuring plugin options
Some plugins can be configured and accept their own options. In that case, use the `[plugin, pluginOptions]` syntax, like so:
```jsx {10-13} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.js'),
// ...
remarkPlugins: [
plugin1,
[plugin2, {option1: {...}}],
],
},
},
],
],
};
```
See more information in the [MDX documentation](https://mdxjs.com/advanced/plugins).
## Tabs
To show tabbed content within Markdown files, you can fall back on MDX. Docusaurus provides `<Tabs>` components out-of-the-box.
```jsx
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs
defaultValue="apple"
values={[
{label: 'Apple', value: 'apple'},
{label: 'Orange', value: 'orange'},
{label: 'Banana', value: 'banana'},
]}>
<TabItem value="apple">This is an apple 🍎</TabItem>
<TabItem value="orange">This is an orange 🍊</TabItem>
<TabItem value="banana">This is a banana 🍌</TabItem>
</Tabs>;
```
will result in
<Tabs
defaultValue="apple"
values={[
{label: 'Apple', value: 'apple'},
{label: 'Orange', value: 'orange'},
{label: 'Banana', value: 'banana'},
]}>
<TabItem value="apple">This is an apple 🍎</TabItem>
<TabItem value="orange">This is an orange 🍊</TabItem>
<TabItem value="banana">This is a banana 🍌</TabItem>
</Tabs>
### Syncing tab choices
You may want choices of the same kind of tabs to sync with each other. For example, you might want to provide different instructions for users on Windows vs users on macOS, and you want to changing all OS-specific instructions tabs in one click. To achieve that, you can give all related tabs the same `groupId` prop. Note that doing this will persist the choice in `localStorage` and all `<Tab>` instances with the same `groupId` will update automatically when the value of one of them is changed. Not that `groupID` are globally-namespaced.
```jsx {2,14}
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]
}>
<TabItem value="win">Use Ctrl + C to copy.</TabItem>
<TabItem value="mac">Use Command + C to copy.</TabItem>
</Tabs>
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]
}>
<TabItem value="win">Use Ctrl + V to paste.</TabItem>
<TabItem value="mac">Use Command + V to paste.</TabItem>
</Tabs>
```
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]}>
<TabItem value="win">Use Ctrl + C to copy.</TabItem>
<TabItem value="mac">Use Command + C to copy.</TabItem>
</Tabs>
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]}>
<TabItem value="win">Use Ctrl + V to paste.</TabItem>
<TabItem value="mac">Use Command + V to paste.</TabItem>
</Tabs>
---
Tab choices with different `groupId`s will not interfere with each other:
```jsx {2,14}
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]
}>
<TabItem value="win">Windows in windows.</TabItem>
<TabItem value="mac">macOS is macOS.</TabItem>
</Tabs>
<Tabs
groupId="non-mac-operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'Unix', value: 'unix'},
]
}>
<TabItem value="win">Windows is windows.</TabItem>
<TabItem value="unix">Unix is unix.</TabItem>
</Tabs>
```
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]}>
<TabItem value="win">Windows in windows.</TabItem>
<TabItem value="mac">macOS is macOS.</TabItem>
</Tabs>
<Tabs
groupId="non-mac-operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'Unix', value: 'unix'},
]}>
<TabItem value="win">Windows is windows.</TabItem>
<TabItem value="unix">Unix is unix.</TabItem>
</Tabs>
## Callouts/admonitions
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:
:::note
The content and title *can* include markdown.
:::
:::tip You can specify an optional title
Heads up! Here's a pro-tip.
:::
:::info
Useful information.
:::
:::caution
Warning! You better pay attention!
:::
:::danger
Danger danger, mayday!
:::
:::note
The content and title _can_ include markdown.
:::
:::tip You can specify an optional title
Heads up! Here's a pro-tip.
:::
:::info
Useful information.
:::
:::caution
Warning! You better pay attention!
:::
:::danger
Danger danger, mayday!
:::
### Specifying title
You may also specify an optional title
:::note Your Title
The content and title *can* include markdown.
:::
:::note Your Title
The content and title _can_ include Markdown.
:::
## Code blocks
Code blocks within documentation are super-powered 💪.
### Code title
You can add a title to the code block by adding `title` key after the language (leave a space between them).
```jsx title="/src/components/HelloCodeTitle.js"
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
```
```jsx title="/src/components/HelloCodeTitle.js"
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
```
### 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 specifications of MDX.
```jsx
console.log('Every repo must come with a mascot.');
```
<!-- TODO: We need to allow users to pick syntax highlighting themes (maybe other than swizzling) -->
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).
```jsx
console.log('Every repo must come with a mascot.');
```
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 {4} title="docusaurus.config.js"
module.exports = {
themeConfig: {
prism: {
theme: require('prism-react-renderer/themes/dracula'),
},
},
};
```
By default, Docusaurus comes with this subset of [commonly used languages](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/vendor/prism/includeLangs.js).
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.
For example, if you want to add highlighting for the `powershell` language:
```js {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
prism: {
additionalLanguages: ['powershell'],
},
// ...
},
};
```
### Line highlighting
You can bring emphasis to certain lines of code by specifying line ranges after the language meta string (leave a space after the language).
```jsx {3}
function HighlightSomeText(highlight) {
if (highlight) {
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
```
```jsx {3}
function HighlightSomeText(highlight) {
if (highlight) {
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
```
To accomplish this, Docusaurus adds the `docusaurus-highlight-code-line` class to the highlighted lines. You will need to define your own styling for this CSS, possibly in your `src/css/custom.css` with a custom background color which is dependent on 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"
.docusaurus-highlight-code-line {
background-color: rgb(72, 77, 91);
display: block;
margin: 0 calc(-1 * var(--ifm-pre-padding));
padding: 0 var(--ifm-pre-padding);
}
/* If you have a different syntax highlighting theme for dark mode. */
html[data-theme='dark'] .docusaurus-highlight-code-line {
background-color: ; /* Color which works with dark mode syntax highlighting theme */
}
```
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.
```jsx {1,4-6,11}
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;
```
```jsx {1,4-6,11}
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;
```
You can also use comments with `highlight-next-line`, `highlight-start`, and `highlight-end` to select which lines are highlighted.
```jsx
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';
}
```
```jsx
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';
}
```
Supported commenting syntax:
| Language | Syntax |
| ---------- | ------------------------ |
| JavaScript | `/* ... */` and `// ...` |
| JSX | `{/* ... */}` |
| Python | `# ...` |
| HTML | `<!-- ... -->` |
If there's a syntax that is not currently supported, we are open to adding them! Pull requests welcome.
### 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.
```jsx live
function Clock(props) {
const [date, setDate] = useState(new Date());
useEffect(() => {
var timerID = setInterval(() => tick(), 1000);
return function cleanup() {
clearInterval(timerID);
};
});
function tick() {
setDate(new Date());
}
return (
<div>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
```
The code block will be rendered as an interactive editor. Changes to the code will reflect on the result panel live.
```jsx live
function Clock(props) {
const [date, setDate] = useState(new Date());
useEffect(() => {
var timerID = setInterval(() => tick(), 1000);
return function cleanup() {
clearInterval(timerID);
};
});
function tick() {
setDate(new Date());
}
return (
<div>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
```
### Multi-language support code blocks
With MDX, you can easily create interactive components within your documentation, for example, to display code in multiple programming languages and switching between them using a tabs component.
Instead of implementing a dedicated component for multi-language support code blocks, we've implemented a generic Tabs component in the classic theme so that you can use it for other non-code scenarios as well.
The following example is how you can have multi-language code tabs in your docs. Note that the empty lines above and below each language block is **intentional**. This is a current limitation of MDX, you have to leave empty lines around Markdown syntax for the MDX parser to know that it's Markdown syntax and not JSX.
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs
defaultValue="js"
values={[
{ label: 'JavaScript', value: 'js', },
{ label: 'Python', value: 'py', },
{ label: 'Java', value: 'java', },
]
}>
<TabItem value="js">
```js
function helloWorld() {
console.log('Hello, world!');
}
```
</TabItem>
<TabItem value="py">
```py
def hello_world():
print 'Hello, world!'
```
</TabItem>
<TabItem value="java">
```java
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
```
</TabItem>
</Tabs>
And you will get the following:
<Tabs
defaultValue="js"
values={[
{ label: 'JavaScript', value: 'js', },
{ label: 'Python', value: 'py', },
{ label: 'Java', value: 'java', },
]
}>
<TabItem value="js">
```js
function helloWorld() {
console.log('Hello, world!');
}
```
</TabItem>
<TabItem value="py">
```py
def hello_world():
print 'Hello, world!'
```
</TabItem>
<TabItem value="java">
```java
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
```
</TabItem>
</Tabs>
You may want to implement your own `<MultiLanguageCode />` abstraction if you find the above approach too verbose. We might just implement one in future for convenience.
If you have multiple of these multi-language code tabs, and you want to sync the selection across the tab instances, refer to the [Syncing tab choices section](#syncing-tab-choices).

View file

@ -0,0 +1,693 @@
---
id: migrating-from-v1-to-v2
title: Migrating from v1 to v2
---
import ColorGenerator from '@site/src/components/ColorGenerator';
:::caution
This migration guide is targeted at Docusaurus users without translation and/or versioning features.
:::
This doc guides you through migrating an existing Docusaurus 1 site to Docusaurus 2. Your Docusaurus 1 site should have the following structure:
```sh
├── docs
└── website
├── blog
├── core
│ └── Footer.js
├── package.json
├── pages
├── sidebars.json
├── siteConfig.js
└── static
```
## Project setup
### `package.json`
#### Scoped package names
In Docusaurus 2, we use scoped package names:
- `docusaurus` -> `@docusaurus/core`
This provides a clear distinction between Docusaurus' official packages and community maintained packages. In another words, all Docusaurus' official packages are namespaced under `@docusaurus/`.
Meanwhile, the default doc site functionalities provided by Docusaurus 1 are now provided by `@docusaurus/preset-classic`. Therefore, we need to add this dependency as well:
```diff title="package.json"
{
dependencies: {
- "docusaurus": "^1.x.x",
+ "@docusaurus/core": "^2.0.0-alpha.48",
+ "@docusaurus/preset-classic": "^2.0.0-alpha.48",
}
}
```
:::tip
Please use the most recent Docusaurus 2 alpha version, which you can check out [here](https://www.npmjs.com/package/@docusaurus/core) (it's tagged `next`).
:::
#### CLI commands
Meanwhile, CLI commands are renamed to `docusaurus <command>` (instead of `docusaurus-command`).
The `"scripts"` section of your `package.json` should be updated as follows:
```json {3-6} title="package.json"
{
"scripts": {
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy"
// ...
}
}
```
A typical Docusaurus 2 `package.json` may look like this:
```json title="package.json"
{
"scripts": {
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy"
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.40",
"@docusaurus/preset-classic": "^2.0.0-alpha.40",
"classnames": "^2.2.6",
"react": "^16.10.2",
"react-dom": "^16.10.2"
},
"browserslist": {
"production": [">0.2%", "not dead", "not op_mini all"],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
```
### Update references to the `build` directory
In Docusaurus 1, all the build artifacts are located within `website/build/<PROJECT_NAME>`. However, in Docusaurus 2, it is now moved to just `website/build`. Make sure that you update your deployment configuration to read the generated files from the correct `build` directory.
If you are deploying to GitHub pages, make sure to run `yarn deploy` instead of `yarn publish-gh-pages` script.
### `.gitignore`
The `.gitignore` in your `website` should contain:
```bash title=".gitignore"
# dependencies
/node_modules
# production
/build
# generated files
.docusaurus
.cache-loader
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
```
## Site configurations
### `docusaurus.config.js`
Rename `siteConfig.js` to `docusaurus.config.js`. In Docusaurus 2, we split each functionality (blog, docs, pages) into plugins for modularity. Presets are bundles of plugins and for backward compatibility we built a `@docusaurus/preset-classic` preset which bundles most of the essential plugins present in Docusaurus 1.
Add the following preset configuration to your `docusaurus.config.js`.
```jsx title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
// Docs folder path relative to website dir.
path: '../docs',
// Sidebars file relative to website dir.
sidebarPath: require.resolve('./sidebars.json'),
},
// ...
},
],
],
};
```
We recommend moving the `docs` folder into the `website` folder and that is also the default directory structure in v2. [Now](https://zeit.co/now) supports [Docusaurus project deployments out-of-the-box](https://github.com/zeit/now-examples/tree/master/docusaurus) if the `docs` directory is within the `website`. It is also generally better for the docs to be within the website so that the docs and the rest of the website code are co-located within one `website` directory.
Refer to migration guide below for each field in `siteConfig.js`.
### Updated fields
#### `baseUrl`, `tagline`, `title`, `url`, `favicon`, `organizationName`, `projectName`, `githubHost`, `scripts`, `stylesheets`
No actions needed.
#### `colors`
Deprecated. We wrote a custom CSS framework for Docusaurus 2 called Infima which uses CSS variables for theming. The docs are not quite ready yet and we will update here when it is. To overwrite Infima's CSS variables, create your own CSS file (e.g. `./src/css/custom.css`) and import it globally by passing it as an option to `@docusaurus/preset-classic`:
```js {7-9} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
};
```
Infima uses 7 shades of each color.
```css title="/src/css/custom.css"
/**
* You can override the default Infima variables here.
* Note: this is not a complete list of --ifm- variables.
*/
:root {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: rgb(33, 175, 144);
--ifm-color-primary-darker: rgb(31, 165, 136);
--ifm-color-primary-darkest: rgb(26, 136, 112);
--ifm-color-primary-light: rgb(70, 203, 174);
--ifm-color-primary-lighter: rgb(102, 212, 189);
--ifm-color-primary-lightest: rgb(146, 224, 208);
}
```
We recommend using [ColorBox](https://www.colorbox.io/) to find the different shades of colors for your chosen primary color.
Alteratively, use the following tool to generate the different shades for your website and copy the variables into `src/css/custom.css`.
<ColorGenerator/>
#### `footerIcon`, `copyright`, `ogImage`, `twitterImage`, `docsSideNavCollapsible`
Site meta info such as assets, SEO, copyright info are now handled by themes. To customize them, use the `themeConfig` field in your `docusaurus.config.js`:
```jsx title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
footer: {
logo: {
alt: 'Facebook Open Source Logo',
src: 'https://docusaurus.io/img/oss_logo.png',
href: 'https://opensource.facebook.com/',
},
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`, // You can also put own HTML here.
},
image: 'img/docusaurus.png',
// Equivalent to `docsSideNavCollapsible`.
sidebarCollapsible: false,
// ...
},
};
```
#### `headerIcon`, `headerLinks`
In Docusaurus 1, header icon and header links were root fields in `siteConfig`:
```js title="siteConfig.js"
headerIcon: 'img/docusaurus.svg',
headerLinks: [
{ doc: "doc1", label: "Getting Started" },
{ page: "help", label: "Help" },
{ href: "https://github.com/", label: "GitHub" },
{ blog: true, label: "Blog" },
],
```
Now, these two fields are both handled by the theme:
```jsx {6-19} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
title: 'Docusaurus',
logo: {
alt: 'Docusaurus Logo',
src: 'img/docusaurus.svg',
},
links: [
{to: 'docs/doc1', label: 'Getting Started', position: 'left'},
{to: 'help', label: 'Help', position: 'left'},
{
href: 'https://github.com/',
label: 'GitHub',
position: 'right',
},
{to: 'blog', label: 'Blog', position: 'left'},
],
},
// ...
},
};
```
#### `algolia`
```jsx {4-8} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
algolia: {
apiKey: '47ecd3b21be71c5822571b9f59e52544',
indexName: 'docusaurus-2',
algoliaOptions: { //... },
},
// ...
},
};
```
#### `blogSidebarCount`
Deprecated. Pass it as a blog option to `@docusaurus/preset-classic` instead:
```jsx {8} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
postsPerPage: 10,
},
// ...
},
],
],
};
```
#### `cname`
Deprecated. Create a `CNAME` file in your `static` folder instead with your custom domain. Files in the `static` folder will be copied into the root of the `build` folder during execution of the build command.
#### `customDocsPath`, `docsUrl`, `editUrl`, `enableUpdateBy`, `enableUpdateTime`
**BREAKING**: `editUrl` should point to (website) docusaurus project instead of `docs` directory.
Deprecated. Pass it as an option to `@docusaurus/preset-classic` docs instead:
```jsx {8-20} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
// Equivalent to `customDocsPath`.
path: 'docs',
// Equivalent to `editUrl` but should point to `website` dir instead of `website/docs`.
editUrl: 'https://github.com/facebook/docusaurus/edit/master/website',
// Equivalent to `docsUrl`.
routeBasePath: 'docs',
// Remark and Rehype plugins passed to MDX. Replaces `markdownOptions` and `markdownPlugins`.
remarkPlugins: [],
rehypePlugins: [],
// Equivalent to `enableUpdateBy`.
showLastUpdateAuthor: true,
// Equivalent to `enableUpdateTime`.
showLastUpdateTime: true,
},
// ...
},
],
],
};
```
#### `gaTrackingId`
```jsx {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
googleAnalytics: {
trackingID: 'UA-141789564-1',
},
// ...
},
};
```
#### `gaGtag`
```jsx {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
gtag: {
trackingID: 'UA-141789564-1',
},
// ...
},
};
```
### Removed fields
The following fields are all deprecated, you may remove from your configuration file.
- `blogSidebarTitle`
- `cleanUrl` - Clean URL is used by default now.
- `defaultVersionShown` - Versioning is not ported yet. You'd be unable to migration to Docusaurus 2 if you are using versioning. Stay tuned.
- `disableHeaderTitle`
- `disableTitleTagline`
- `docsSideNavCollapsible` is available at `themeConfig.sidebarCollapsible`, and this is turned on by default now.
- `facebookAppId`
- `facebookComments`
- `facebookPixelId`
- `fonts`
- `highlight` - We now use [Prism](https://prismjs.com/) instead of [highlight.js](https://highlightjs.org/).
- `markdownOptions` - We use MDX in v2 instead of Remarkable. Your markdown options have to be converted to Remark/Rehype plugins.
- `markdownPlugins` - We use MDX in v2 instead of Remarkable. Your markdown plugins have to be converted to Remark/Rehype plugins.
- `manifest`
- `noIndex`
- `onPageNav` - This is turned on by default now.
- `separateCss` - It can imported in the same manner as `custom.css` mentioned above.
- `scrollToTop`
- `scrollToTopOptions`
- `translationRecruitingLink`
- `twitter`
- `twitterUsername`
- `useEnglishUrl`
- `users`
- `usePrism` - We now use [Prism](https://prismjs.com/) instead of [highlight.js](https://highlightjs.org/)
- `wrapPagesHTML`
We intend to implement many of the deprecated config fields as plugins in future. Help will be appreciated!
## Components
### Sidebar
In previous version, nested sidebar category is not allowed and sidebar category can only contain doc id. However, v2 allows infinite nested sidebar and we have many types of [Sidebar Item](docs.md#sidebar-item) other than document.
You'll have to migrate your sidebar if it contains category type. Rename `subcategory` to `category` and `ids` to `items`.
```diff title="sidebars.json"
{
- type: 'subcategory',
+ type: 'category',
label: 'My Example Subcategory',
+ items: ['doc1'],
- ids: ['doc1']
},
```
### Footer
`website/core/Footer.js` is no longer needed. If you want to modify the default footer provided by Docusaurus, [swizzle](using-themes.md#swizzling-theme-components) it:
```bash npm2yarn
npm run swizzle @docusaurus/theme-classic Footer
```
This will copy the current `<Footer />` component used by the theme to a `src/theme/Footer` directory under the root of your site, you may then edit this component for customization.
### Pages
Please refer to [creating pages](creating-pages.md) to learn how Docusaurus 2 pages work. After reading that, notice that you have to move `pages/en` files in v1 to `src/pages` instead.
`CompLibrary` is deprecated in v2, so you have to write your own React component or use Infima styles (Docs will be available soon, sorry about that! In the meanwhile, inspect the V2 website or view https://facebookincubator.github.io/infima/ to see what styles are available).
The following code could be helpful for migration of various pages:
- Index page - [Flux](https://github.com/facebook/flux/blob/master/website/src/pages/index.js/) (recommended), [Docusaurus 2](https://github.com/facebook/docusaurus/blob/master/website/src/pages/index.js/), [Hermes](https://github.com/facebook/hermes/blob/master/website/src/pages/index.js/)
- Help/Support page - [Docusaurus 2](https://github.com/facebook/docusaurus/blob/master/website/src/pages/help.js/), [Flux](http://facebook.github.io/flux/support)
## Content
### Remove AUTOGENERATED_TABLE_OF_CONTENTS
This feature is deprecated. You may read more about it in [this issue](https://github.com/facebook/docusaurus/issues/1549). If you need the feature, use [remark-toc](https://github.com/remarkjs/remark-toc) instead and pass it to docs plugin's `remarkPlugins` option.
### Update Markdown syntax to be MDX-compatible
In Docusaurus 2, the markdown syntax has been changed to [MDX](https://mdxjs.com/). Hence there might be some broken syntax in the existing docs which you would have to update. A common example is self-closing tags like `<img>` and `<br>` which are valid in HTML would have to be explicitly closed now ( `<img/>` and `<br/>`). All tags in MDX documents have to be valid JSX.
**Tips**: You might want to use some online tools like [HTML to JSX](https://transform.tools/html-to-jsx) to make the migration easier.
### Language-specific code tabs
Refer to the [multi-language support code blocks](markdown-features.mdx#multi-language-support-code-blocks) section.
### Front matter
The Docusaurus front matter fields for the blog have been changed from camelCase to snake_case to be consistent with the docs.
The fields `authorFBID` and `authorTwitter` have been deprecated. They are only used for generating the profile image of the author which can be done via the `author_image_url` field.
## Test your site
After migration, your folder structure should look like this:
```sh
my-project
├── docs
└── website
├── blog
├── src
│ ├── css
│ │ └── custom.css
│ └── pages
│ └── index.js
├── package.json
├── sidebars.json
├── .gitignore
├── docusaurus.config.js
└── static
```
Start the development server and fix any errors:
```bash
cd website
yarn start
```
## Example migration PRs
You might want to refer to our migration PRs for [Create React App](https://github.com/facebook/create-react-app/pull/7785) and [Flux](https://github.com/facebook/flux/pull/471) as examples of how a migration for a basic Docusaurus v1 site can be done.
## Support
For any questions, you can ask in the [`#docusaurus-1-to-2-migration` Discord channel](https://discordapp.com/invite/kYaNd6V). Feel free to tag [@yangshun](https://github.com/yangshun) in any migration PRs if you would like us to have a look.
## Versioned Site
:::caution
The versioning feature is a work in progress! Although we've implemented docs versioning since `2.0.0-alpha.37`, we'd like to test it out for v2 users first before we recommend v1 users to migrate to v2. There are some changes in how v2 versioning works compared to v1. In the future, we might create a script to migrate your versioned docs easier. However, if you are adventurous enough to manually migrate, feel free to do so. Be warned though, the manual migration requires lot of work.
:::
## Changes from v1
Read up https://v2.docusaurus.io/blog/2018/09/11/Towards-Docusaurus-2#versioning first for problems in v1's approach.
### Migrate your `versioned_docs` front matter
Unlike v1, The markdown header for each versioned doc is no longer altered by using `version-${version}-${original_id}` as the value for the actual id field. See scenario below for better explanation.
For example, if you have a `docs/hello.md`.
```md
---
id: hello
title: Hello, World !
---
Hi, Endilie here :)
```
When you cut a new version 1.0.0, in Docusaurus v1, `website/versioned_docs/version-1.0.0/hello.md` looks like this:
```md
---
id: version-1.0.0-hello
title: Hello, World !
original_id: hello
---
Hi, Endilie here :)
```
In comparison, Docusaurus 2 `website/versioned_docs/version-1.0.0/hello.md` looks like this (exactly same as original)
```md
---
id: hello
title: Hello, World !
---
Hi, Endilie here :)
```
Since we're going for snapshot and allow people to move (and edit) docs easily inside version. The `id` frontmatter is no longer altered and will remain the same. Internally, it is set as `version-${version}/${id}`.
Essentially, here are the necessary changes in each versioned_docs file:
```diff {2-3,5}
---
- id: version-1.0.0-hello
+ id: hello
title: Hello, World !
- original_id: hello
---
Hi, Endilie here :)
```
### Migrate your `versioned_sidebars`
- Refer to `versioned_docs` id as `version-${version}/${id}` (v2) instead of `version-${version}-${original_id}` (v1).
Because in v1 there is a good chance someone created a new file with front matter id `"version-${version}-${id}"` that can conflict with `versioned_docs` id.
For example, Docusaurus 1 can't differentiate `docs/xxx.md`
```md
---
id: version-1.0.0-hello
---
Another content
```
vs `website/versioned_docs/version-1.0.0/hello.md`
```md
---
id: version-1.0.0-hello
title: Hello, World !
original_id: hello
---
Hi, Endilie here :)
```
Since we don't allow `/` in v1 & v2 for frontmatter, conflicts are less likely to occur.
So v1 users need to migrate their versioned_sidebars file
Example `versioned_sidebars/version-1.0.0-sidebars.json`:
```diff {2-3,5-6,9-10} title="versioned_sidebars/version-1.0.0-sidebars.json"
{
+ "version-1.0.0/docs": {
- "version-1.0.0-docs": {
"Test": [
+ "version-1.0.0/foo/bar",
- "version-1.0.0-foo/bar",
],
"Guides": [
+ "version-1.0.0/hello",
- "version-1.0.0-hello"
]
}
}
```
### Populate your `versioned_sidebars` and `versioned_docs`
In v2, we use snapshot approach for documentation versioning. **Every versioned docs does not depends on other version**. It is possible to have `foo.md` in `version-1.0.0` but it doesn't exist in `version-1.2.0`. This is not possible in previous version due to Docusaurus v1 fallback functionality (https://docusaurus.io/docs/en/versioning#fallback-functionality).
For example, if your `versions.json` looks like this in v1
```json title="versions.json"
["1.1.0", "1.0.0"]
```
Docusaurus v1 creates versioned docs **if and only if the doc content is different**. Your docs structure might look like this if the only doc changed from v1.0.0 to v1.1.0 is `hello.md`.
```shell
website
├── versioned_docs
│ ├── version-1.1.0
│ │ └── hello.md
│ └── version-1.0.0
│ ├── foo
│ │ └── bar.md
│ └── hello.md
├── versioned_sidebars
│ └── version-1.0.0-sidebars.json
```
In v2, you have to populate the missing `versioned_docs` and `versioned_sidebars` (with the right frontmatter and id reference too).
```shell {3-5,12}
website
├── versioned_docs
│ ├── version-1.1.0
│ │ ├── foo
│ │ │ └── bar.md
│ │ └── hello.md
│ └── version-1.0.0
│ ├── foo
│ │ └── bar.md
│ └── hello.md
├── versioned_sidebars
│ ├── version-1.1.0-sidebars.json
│ └── version-1.0.0-sidebars.json
```
### Convert style attributes to style objects in MDX
Docusaurus 2 uses JSX for doc files. If you have any style attributes in your Docusaurus 1 docs, convert them to style objects, like this:
```diff
---
id: demo
title: Demo
---
## Section
hello world
- pre style="background: black">zzz</pre>
+ pre style={{background: 'black'}}>zzz</pre>
```

View file

@ -0,0 +1,142 @@
---
id: presets
title: Presets
---
Presets are collections of plugins and themes.
## Using presets
A preset is usually a npm package, so you install them like other npm packages using npm.
```bash npm2yarn
npm install --save docusaurus-preset-name
```
Then, add it in your site's `docusaurus.config.js`'s `presets` option:
```jsx {3} title="docusaurus.config.js"
module.exports = {
// ...
presets: ['@docusaurus/preset-xxxx'],
};
```
To load presets from your local directory, specify how to resolve them:
```jsx {5} title="docusaurus.config.js"
const path = require('path');
module.exports = {
// ...
presets: [path.resolve(__dirname, '/path/to/docusaurus-local-presets')],
};
```
## Presets -> themes and plugins
Presets in some way are a shorthand function to add plugins and themes to your docusaurus config. For example, you can specify a preset that includes the following themes and plugins,
```js
module.exports = function preset(context, opts = {}) {
return {
themes: [
require.resolve('@docusaurus/themes-cool'),
require.resolve('@docusaurus/themes-bootstrap'),
],
plugins: [require.resolve('@docusaurus/plugin-blog')],
};
};
```
then in your Docusaurus config, you may configure the preset instead:
```jsx {3} title="docusaurus.config.js"
module.exports = {
// ...
presets: ['@docusaurus/preset-my-own'],
};
```
This is equivalent of doing:
```jsx title="docusaurus.config.js"
module.exports = {
themes: ['@docusaurus/themes-cool', '@docusaurus/themes-bootstrap'],
plugins: ['@docusaurus/plugin-blog'],
};
```
This is especially useful when some plugins and themes are intended to be used together.
## Official presets
### `@docusaurus/preset-classic`
The classic preset that is usually shipped by default to new docusaurus website. It is a set of plugins and themes.
| Themes | Plugins |
| ---------------------------------- | ------------------------------------- |
| `@docusaurus/theme-classic` | `@docusaurus/plugin-content-docs` |
| `@docusaurus/theme-search-algolia` | `@docusaurus/plugin-content-blog` |
| | `@docusaurus/plugin-content-pages` |
| | `@docusaurus/plugin-google-analytics` |
| | `@docusaurus/plugin-google-gtag` |
| | `@docusaurus/plugin-sitemap` |
To specify plugin options individually, you can provide the necessary fields to certain plugins, i.e. `customCss` for `@docusaurus/theme-classic`, pass them in the preset field, like this:
```js title="docusaurus.config.js"
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
// Will be passed to @docusaurus/theme-classic.
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
// Will be passed to @docusaurus/plugin-content-docs
docs: {},
// Will be passed to @docusaurus/plugin-content-blog
blog: {},
// Will be passed to @docusaurus/plugin-content-pages
pages: {},
// Will be passed to @docusaurus/plugin-content-sitemap
sitemap: {},
},
],
],
};
```
In addition to these plugins and themes, `@docusaurus/theme-classic` adds [`remark-admonitions`](https://github.com/elviswolcott/remark-admonitions) as a remark plugin to `@docusaurus/plugin-content-blog` and `@docusaurus/plugin-content-docs`.
The `admonitions` key will be passed as the [options](https://github.com/elviswolcott/remark-admonitions#options) to `remark-admonitions`. Passing `false` will prevent the plugin from being added to MDX.
```js title="docusaurus.config.js"
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
// options for remark-admonitions
admonitions: {},
},
},
],
],
};
```
<!--
Advanced guide on using and configuring presets
References
---
- [classic themes](/packages/docusaurus-preset-classic/src/index.js)
- [babel docs on presets](https://babeljs.io/docs/en/presets)
-->

View file

@ -0,0 +1,45 @@
---
id: resources
title: Awesome Resources
---
A curated list of interesting Docusaurus community projects.
## Videos
- [F8 2019: Using Docusaurus to Create Open Source Websites](https://www.youtube.com/watch?v=QcGJsf6mgZE)
## Articles
- [Live code editing in Docusaurus](https://dev.to/mrmuhammadali/live-code-editing-in-docusaurus-28k)
## Showcase
See the <a href={require('@docusaurus/useBaseUrl').default('showcase')}>showcase</a>.
## Official plugins
- [@docusaurus/plugin-content-blog](using-plugins.md#docusaurusplugin-content-blog)
- [@docusaurus/plugin-content-docs](using-plugins.md#docusaurusplugin-content-docs)
- [@docusaurus/plugin-content-pages](using-plugins.md#docusaurusplugin-content-pages)
- [@docusaurus/plugin-google-analytics](using-plugins.md#docusaurusplugin-google-analytics)
- [@docusaurus/plugin-google-gtag](using-plugins.md#docusaurusplugin-google-gtag)
- [@docusaurus/plugin-sitemap](using-plugins.md#docusaurusplugin-sitemap)
- [@docusaurus/plugin-ideal-image](using-plugins.md#docusaurusplugin-ideal-image)
## Community plugins
- [docusaurus-plugin-lunr](https://github.com/daldridge/docusaurus-plugin-lunr) - Docusaurus v2 plugin to create a local search index for use with Lunr.js
- [docusaurus-lunr-search](https://github.com/lelouch77/docusurus-lunr-search) - Offline Search for Docusaurus v2
- [docusaurus-search-local](https://github.com/cmfcmf/docusaurus-search-local) - Offline/local search for Docusaurus v2
- [docusaurus-pdf](https://github.com/KohheePeace/docusaurus-pdf) - Generate documentation into PDF format
- [docusaurus-plugin-sass](https://github.com/rlamana/docusaurus-plugin-sass) - Sass/SCSS stylesheets support
- [docusaurus2-dotenv](https://github.com/jonnynabors/docusaurus2-dotenv) - A Docusaurus 2 plugin that supports dotenv and other environment variables
## Enterprise usage
- Facebook
- Google
- Stripe
- Algolia
- Callstack

View file

@ -0,0 +1,56 @@
---
id: search
title: Search
keywords:
- algolia
- search
---
Docusaurus' own `@docusaurus/preset-classic` supports a search integration.
There are two main options, you can use [Algolia DocSearch](https://community.algolia.com/docsearch/) or bring in your own `SearchBar` component.
## Using Algolia DocSearch
Algolia DocSearch works by crawling the content of your website every 24 hours and putting all the content in an Algolia index. This content is then queried directly from your front-end using the Algolia API. Note that your website needs to be publicly available for this to work (i.e., not behind a firewall). The service is free.
### Connecting Algolia
To connect your docs with Algolia, add an `algolia` field in your `themeConfig`. Note that you will need algolia API key and algolia index. You can [apply for DocSearch here](https://docsearch.algolia.com/apply/).
```jsx title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
// ...
// highlight-start
algolia: {
apiKey: 'api-key',
indexName: 'index-name',
appId: 'app-id', // Optional, if you run the DocSearch crawler on your own
algoliaOptions: {}, // Optional, if provided by Algolia
},
// highlight-end
},
};
```
### Customizing the Algolia search bar
If you prefer to customize Algolia's search bar React component, swizzle the `SearchBar` component in `@docusaurus/theme-search-algolia`:
```bash npm2yarn
npm run swizzle @docusaurus/theme-search-algolia SearchBar
```
## Using your own search
To use your own search, swizzle the `SearchBar` component in `@docusaurus/theme-classic`
```bash npm2yarn
npm run swizzle @docusaurus/theme-classic SearchBar
```
This will create a `src/themes/SearchBar` file in your project folder. Restart your dev server and edit the component, you will see that Docusaurus uses your own `SearchBar` component now.
**Notes**: You can alternatively [swizzle from Algolia SearchBar](#customizing-the-algolia-search-bar) and create your own search component from there.

View file

@ -0,0 +1,64 @@
---
id: static-assets
title: Static Assets
---
In general, every website needs assets: images, stylesheets, favicons and etc. In such cases, you can create a directory named `static` at the root of your project. Every file you put into that directory will be copied into the the root of the generated `build` folder with the directory hierarchy preserved. E.g. if you add a file named `sun.jpg` to the static folder, itll be copied to `build/sun.jpg`.
This means that if the site's `baseUrl` is `/`, an image in `/static/img/docusaurus_keytar.svg` is available at `/img/docusaurus_keytar.svg`.
## Referencing your static asset
You can reference assets from the `static` folder in your code. You could use hardcoded absolute paths, i.e. starting with a slash /, but remember to include the `baseUrl` if it is not `/`. However, this will break if you change your `baseUrl` in the config.
A better way would be to use the `useBaseUrl` utility function which appends the `baseUrl` to paths for you.
### JSX example
```jsx title="MyComponent.js"
import useBaseUrl from '@docusaurus/useBaseUrl';
<img
alt="Docusaurus with Keytar"
src={useBaseUrl('img/docusaurus_keytar.svg')}
/>;
```
You can also import SVG images, which will be transformed into React components.
```jsx title="MyComponent.js"
import DocusaurusLogoWithKeytar from '@site/static/img/docusaurus_keytar.svg';
<DocusaurusLogoWithKeytar title="Docusaurus Logo" className="logo" />;
```
### Markdown example
Thanks to MDX, you can also use `useBaseUrl` utility function in Markdown files! You'd have to use `<img>` tags instead of the Markdown image syntax though. The syntax is exactly the same as in JSX.
```jsx title="my-doc.mdx"
---
id: my-doc
title: My Doc
---
// Add to the top of the file below the front matter.
import useBaseUrl from '@docusaurus/useBaseUrl';
...
<img alt="Docusaurus with Keytar" src={useBaseUrl('img/docusaurus_keytar.svg')} />
```
You could also just use Markdown image syntax, but you would have to manually maintain the image paths yourself and isn't recommended.
```md title="my-doc.md"
![Docusaurus with Keytar](/img/docusaurus_keytar.png)
```
### Caveats
Keep in mind that:
- By default, none of the files in `static` folder will be post-processed or minified.
- Missing files references via hardcoded absolute paths will not be detected at compilation time, and will result in a 404 error.

View file

@ -0,0 +1,200 @@
---
id: styling-layout
title: Styling and Layout
description: A Docusaurus site is a pre-rendered single-page React application. You can style it the way you style React apps.
---
import ColorGenerator from '@site/src/components/ColorGenerator';
## Traditional CSS
If you're using `@docusaurus/preset-classic`, you can create your own CSS files (e.g. `/src/css/custom.css`) and import them globally by passing it as an option into the preset.
```js title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
// highlight-start
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
// highlight-end
},
],
],
};
```
Any CSS you write within that file will be available globally and can be referenced directly using string literals. This is the most traditional approach to writing CSS and is fine for small websites that do not have much customization.
## Styling your site with Infima
`@docusaurus/preset-classic` uses [Infima](https://facebookincubator.github.io/infima/) as the underlying styling framework. Infima provides flexible layout and common UI components styling suitable for content-centric websites (blogs, documentation, landing pages). For more details, check out the [Infima website](https://facebookincubator.github.io/infima/).
When you `init` your Docusaurus 2 project, the website will be generated with basic Infima stylesheets and default styling. You may customize the styling by editing the `/src/css/custom.css` file.
```css title="/src/css/custom.css"
/**
* You can override the default Infima variables here.
* Note: this is not a complete list of --ifm- variables.
*/
:root {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: rgb(33, 175, 144);
--ifm-color-primary-darker: rgb(31, 165, 136);
--ifm-color-primary-darkest: rgb(26, 136, 112);
--ifm-color-primary-light: rgb(70, 203, 174);
--ifm-color-primary-lighter: rgb(102, 212, 189);
--ifm-color-primary-lightest: rgb(146, 224, 208);
--ifm-code-font-size: 95%;
}
```
Infima uses 7 shades of each color. We recommend using [ColorBox](https://www.colorbox.io/) to find the different shades of colors for your chosen primary color.
Alternatively, use the following tool to generate the different shades for your website and copy the variables into `/src/css/custom.css`.
<ColorGenerator/>
<!-- TODO need more refinement here -->
## Styling approaches
A Docusaurus site is a single-page React application. You can style it the way you style React apps.
There are a few approaches/frameworks which will work, depending on your preferences and the type of website you are trying to build. Websites that are highly interactive and behave more like web apps will benefit from a more modern styling approaches that co-locate styles with the components. Component styling can also be particularly useful when you wish to customize or swizzle a component.
### Global styles
This is the most traditional way of styling that most developers (including non-front end developers) would be familiar with.
Assuming you are using `@docusaurus/preset-classic` and `/src/css/custom.css` was passed in to the preset config, styles inside that file would be available globally.
```css title="/src/css/custom.css"
.purple-text {
color: rebeccapurple;
}
```
```jsx
function MyComponent() {
return (
<main>
<h1 className="purple-text">Purple Heading!</h1>
</main>
);
}
```
### CSS modules
To style your components using [CSS Modules](https://github.com/css-modules/css-modules), name your stylesheet files with the `.module.css` suffix (e.g. `welcome.module.css`). webpack will load such CSS files as CSS modules and you have to reference the class names from the imported CSS module (as opposed to using plain strings). This is similar to the convention used in [Create React App](https://facebook.github.io/create-react-app/docs/adding-a-css-modules-stylesheet).
```css title="styles.module.css"
.main {
padding: 12px;
}
.heading {
font-weight: bold;
}
.contents {
color: #ccc;
}
```
```jsx
import styles from './styles.module.css';
function MyComponent() {
return (
<main className={styles.main}>
<h1 className={styles.heading}>Hello!</h1>
<article className={styles.contents}>Lorem Ipsum</article>
</main>
);
}
```
The class names which will be processed by webpack into a globally unique class name during build.
### CSS-in-JS
:::caution
This section is a work in progress. [Welcoming PRs](https://github.com/facebook/docusaurus/issues/1640).
:::
### Sass/SCSS
To use Sass/SCSS as your CSS preprocessor, install the unofficial Docusaurus 2 plugin [`docusaurus-plugin-sass`](https://github.com/rlamana/docusaurus-plugin-sass). This plugin works for both global styles and the CSS modules approach:
1. Install [`docusaurus-plugin-sass`](https://github.com/rlamana/docusaurus-plugin-sass):
```bash npm2yarn
npm install --save docusaurus-plugin-sass
```
2. Include the plugin in your `docusaurus.config.js` file:
```jsx {3} title="docusaurus.config.js"
module.exports = {
// ...
plugins: ['docusaurus-plugin-sass'],
// ...
};
```
3. Write and import your stylesheets in Sass/SCSS as normal.
#### Global styles using Sass/SCSS
You can now set the `customCss` property of `@docusaurus/preset-classic` to point to your Sass/SCSS file:
```jsx {8} title="docusaurus.config.js"
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
// ...
theme: {
customCss: require.resolve('./src/css/custom.scss'),
},
// ...
},
],
],
};
```
#### Modules using Sass/SCSS
Name your stylesheet files with the `.module.scss` suffix (e.g. `welcome.module.scss`) instead of `.css`. Webpack will use `sass-loader` to preprocess your stylesheets and load them as CSS modules.
```scss title="styles.module.scss"
.main {
padding: 12px;
article {
color: #ccc;
}
}
```
```jsx
import styles from './styles.module.scss';
function MyComponent() {
return (
<main className={styles.main}>
<article>Lorem Ipsum</article>
</main>
);
}
```

View file

@ -0,0 +1,31 @@
---
id: support
title: Support
---
Docusaurus has a community of thousands of developers.
On this page we've listed some Docusaurus-related communities that you can be a part of; see the other pages in this section for additional online and in-person learning materials.
Before participating in Docusaurus' communities, [please read our Code of Conduct](https://engineering.fb.com/codeofconduct/). We have adopted the [Contributor Covenant](https://www.contributor-covenant.org/) and we expect that all community members adhere to the guidelines within.
## Stack Overflow
Stack Overflow is a popular forum to ask code-level questions or if you're stuck with a specific error. Read through the [existing questions](https://stackoverflow.com/questions/tagged/docusaurus) tagged with **docusaurus** or [ask your own](https://stackoverflow.com/questions/ask?tags=docusaurus)!
## Discussion forums
There are many online forums which are a great place for discussion about best practices and application architecture as well as the future of Docusaurus. If you have an answerable code-level question, Stack Overflow is usually a better fit.
- [Docusaurus online chat](https://discord.gg/docusaurus)
- [#docusaurus-2-dogfooding](https://discord.gg/7wjJ9yH) for user help
- [#docusaurus-2-dev](https://discord.gg/6g6ASPA) for contributing help
- [Reddit's Docusaurus community](https://www.reddit.com/r/docusaurus/)
## Feature requests
For new feature requests, you can create a post on our [Canny board](/feedback), which is a handy tool for roadmapping and allows for sorting by upvotes, which gives the core team a better indicator of what features are in high demand, as compared to GitHub issues which are harder to triage. Refrain from making a Pull Request for new features (especially large ones) as someone might already be working on it or will be part of our roadmap. Talk to us first!
## News
For the latest news about Docusaurus, [follow **@docusaurus** on Twitter](https://twitter.com/docusaurus) and the [official Docusaurus blog](/blog) on this website.

View file

@ -0,0 +1,174 @@
---
id: team
title: Team
---
## Active Team
<div className="row">
<div className="col col--6 margin-bottom--lg">
<div className="card card--full-height">
<div className="card__header">
<div className="avatar avatar--vertical">
<img
className="avatar__photo avatar__photo--xl"
src="https://github.com/lex111.png"
/>
<div className="avatar__intro">
<h3 className="avatar__name">Alexey Pyltsyn</h3>
</div>
</div>
</div>
<div className="card__body">
Obsessed open-source enthusiast 👋 Eternal amateur at everything 🤷‍♂️ Maintainer of Russian docs on PHP, React, Kubernetes and much more 🧐
</div>
<div className="card__footer">
<div className="button-group button-group--block">
<a className="button button--secondary" href="https://github.com/lex111">GitHub</a>
</div>
</div>
</div>
</div>
<div className="col col--6 margin-bottom--lg">
<div className="card card--full-height">
<div className="card__header">
<div className="avatar avatar--vertical">
<img
className="avatar__photo avatar__photo--xl"
src="https://github.com/fanny.png"
/>
<div className="avatar__intro">
<h3 className="avatar__name">Fanny Vieira</h3>
</div>
</div>
</div>
<div className="card__body">
Fanny got started with web development in high school, building a project for the school kitchen. In her free time she loves contributing to Open Source, occasionally writing on <a href="https://dev.to/fannyvieira" target="_blank">her blog</a> about her experiences, cooking, and creating <a href="https://open.spotify.com/user/anotherfanny" target="_blank">Spotify playlists</a>.
</div>
<div className="card__footer">
<div className="button-group button-group--block">
<a className="button button--secondary" href="https://github.com/fanny">GitHub</a>
<a className="button button--secondary" href="https://twitter.com/fannyvieiira">Twitter</a>
</div>
</div>
</div>
</div>
<div className="col col--6 margin-bottom--lg">
<div className="card card--full-height">
<div className="card__header">
<div className="avatar avatar--vertical">
<img
className="avatar__photo avatar__photo--xl"
src="https://github.com/JoelMarcey.png"
/>
<div className="avatar__intro">
<h3 className="avatar__name">Joel Marcey</h3>
</div>
</div>
</div>
<div className="card__body">
Docusaurus founder and now ever grateful Docusaurus cheerleader to those who actually write code for it.
</div>
<div className="card__footer">
<div className="button-group button-group--block">
<a className="button button--secondary" href="https://github.com/JoelMarcey">GitHub</a>
<a className="button button--secondary" href="https://twitter.com/joelmarcey">Twitter</a>
</div>
</div>
</div>
</div>
<div className="col col--6 margin-bottom--lg">
<div className="card card--full-height">
<div className="card__header">
<div className="avatar avatar--vertical">
<img
className="avatar__photo avatar__photo--xl"
src="https://github.com/yangshun.png"
/>
<div className="avatar__intro">
<h3 className="avatar__name">Yangshun Tay</h3>
</div>
</div>
</div>
<div className="card__body">
Full Front End Stack developer who likes working on the Jamstack. Working on Docusaurus made him Facebook's unofficial part-time Open Source webmaster, which is an awesome role to be in.
</div>
<div className="card__footer">
<div className="button-group button-group--block">
<a className="button button--secondary" href="https://github.com/yangshun">GitHub</a>
<a className="button button--secondary" href="https://twitter.com/yangshunz">Twitter</a>
</div>
</div>
</div>
</div>
</div>
## Honorary Alumni
<div className="row">
<div className="col col--6 margin-bottom--lg">
<div className="card card--full-height">
<div className="card__header">
<div className="avatar avatar--vertical">
<img
className="avatar__photo avatar__photo--xl"
src="https://github.com/endiliey.png"
/>
<div className="avatar__intro">
<h3 className="avatar__name">Endilie Yacop Sucipto</h3>
</div>
</div>
</div>
<div className="card__body">
Maintainer @docusaurus · 🔥🔥🔥
</div>
<div className="card__footer">
<div className="button-group button-group--block">
<a className="button button--secondary" href="https://github.com/endiliey">GitHub</a>
<a className="button button--secondary" href="https://twitter.com/endiliey">Twitter</a>
</div>
</div>
</div>
</div>
<div className="col col--6 margin-bottom--lg">
<div className="card card--full-height">
<div className="card__header">
<div className="avatar avatar--vertical">
<img
className="avatar__photo avatar__photo--xl"
src="https://github.com/wgao19.png"
/>
<div className="avatar__intro">
<h3 className="avatar__name">Wei Gao</h3>
</div>
</div>
</div>
<div className="card__body">
👩🏻‍🌾 Work in progress React developer, maintains Docusaurus, writes docs and spams this world with many websites.
</div>
<div className="card__footer">
<div className="button-group button-group--block">
<a className="button button--secondary" href="https://github.com/wgao19">GitHub</a>
<a className="button button--secondary" href="https://twitter.com/wgao19">Twitter</a>
</div>
</div>
</div>
</div>
</div>
## Acknowledgements
Docusaurus was originally created by Joel Marcey. Today, Docusaurus has a few hundred open source contributors. Wed like to recognize a few people who have made significant contributions to Docusaurus and its documentation in the past and have helped maintain them over the years:
- [Amy Lam](https://github.com/amyrlam)
- [Cheng Lou](https://github.com/chenglou)
- [Christine Abernathy](https://github.com/caabernathy)
- [Christopher Chedeau](https://github.com/vjeux)
- [Elvis Wolcott](https://github.com/elviswolcott)
- [Eric Nakagawa](https://github.com/ericnakagawa)
- [Fienny Angelina](https://github.com/fiennyangeln)
- [Frank Li](https://github.com/deltice)
- [Héctor Ramos](https://github.com/hramos)
- [Ramón Lamana](https://github.com/rlamana)
- [Ricky Vetter](https://github.com/rickyvetter)
- [Sam Zhou](https://github.com/SamChou19815)

View file

@ -0,0 +1,265 @@
---
id: theme-classic
title: '@docusaurus/theme-classic'
---
:::caution
This section is a work in progress.
:::
## Common
### Dark mode
To remove the ability to switch on dark mode, there is an option `themeConfig.disableDarkMode`, which is implicitly set to `false`.
```js {4} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
disableDarkMode: false,
// ...
},
};
```
With the enabled `defaultDarkMode` option you could set dark mode by default. However, in this case, the user's preference will not be taken into account until they manually sets the desired mode via toggle in the navbar.
```js {4} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
defaultDarkMode: true,
// ...
},
};
```
### Meta image
You can configure a default image that will be used for your meta tag, in particular `og:image` and `twitter:image`.
```js {4-6} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
// Relative to your site's "static" directory.
// Cannot be SVGs. Can be external URLs too.
image: 'img/docusaurus.png',
// ...
},
};
```
### 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 dismissable panel above the navbar.
```js {4-10} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
announcementBar: {
id: 'support_us', // Any value that will identify this message.
content:
'We are looking to revamp our docs, please fill <a target="_blank" rel="noopener noreferrer" href="#">this survey</a>',
backgroundColor: '#fafbfc', // Defaults to `#fff`.
textColor: '#091E42', // Defaults to `#000`.
},
// ...
},
};
```
## Hooks
### `useThemeContext`
React hook to access theme context. This context contains functions for setting light and dark mode and boolean property, indicating which mode is currently in use.
Usage example:
```jsx
import React from 'react';
// highlight-next-line
import useThemeContext from '@theme/hooks/useThemeContext';
const Example = () => {
// highlight-next-line
const {isDarkTheme, setLightTheme, setDarkTheme} = useThemeContext();
return <h1>Dark mode is now {isDarkTheme ? 'on' : 'off'}</h1>;
};
```
## Navbar
### Navbar title & logo
You can add a logo and title to the navbar via `themeConfig.navbar`. 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.
```js {5-11} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
title: 'Site Title',
logo: {
alt: 'Site Logo',
src: 'img/logo.svg',
srcDark: 'img/logo_dark.svg', // Default to `logo.src`.
href: 'https://v2.docusaurus.io/', // Default to `siteConfig.baseUrl`.
target: '_self', // By default, this value is calculated based on the `href` attribute (the external link will open in a new tab, all others in the current one).
},
},
// ...
},
};
```
### Navbar links
You can add links to the navbar via `themeConfig.navbar.links`:
```js {5-15} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
links: [
{
// Client-side routing, used for navigating within the website.
// The baseUrl will be automatically prepended to this value.
to: 'docs/introduction',
// A full-page navigation, used for navigating outside of the website.
// You should only use either `to` or `href`.
href: 'https://www.facebook.com',
// Prepends the baseUrl to href values.
prependBaseUrlToHref: true,
// The string to be shown.
label: 'Introduction',
// Left or right side of the navbar.
position: 'left', // or 'right'
// To apply the active class styling on all
// routes starting with this path.
// This usually isn't necessary
activeBasePath: 'docs',
// Alternative to activeBasePath if required.
activeBaseRegex: 'docs/(next|v8)',
// Custom CSS class (for styling any item).
className: '',
},
// ... other links
],
},
// ...
},
};
```
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.
### Navbar dropdown
Navbar items can also be dropdown items by specifying the `items`, an inner array of navbar links.
```js {9-19} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
links: [
{
label: 'Community',
position: 'left', // or 'right'
items: [
{
label: 'Facebook',
href: '...',
},
{
label: 'GitHub',
href: '...',
},
// ... more items
],
},
],
},
// ...
},
};
```
### 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 {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
hideOnScroll: true,
},
// ...
},
};
```
<!--
## Footer
TODO.
-->
## CodeBlock
Docusaurus uses [Prism React Renderer](https://github.com/FormidableLabs/prism-react-renderer) to highlight code blocks.
### 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). If you want to use a different syntax highlighting theme when the site is in dark mode, you may also do so.
```js {5-6} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
prism: {
theme: require('prism-react-renderer/themes/github'),
darkTheme: require('prism-react-renderer/themes/dracula'),
},
// ...
},
};
```
:::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](markdown-features.mdx#line-highlighting).
:::
### 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, e.g.:
```js {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
prism: {
defaultLanguage: 'javascript',
},
// ...
},
};
```

View file

@ -0,0 +1,460 @@
---
id: using-plugins
title: 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 bundle via [presets](presets.md).
## Installing a plugin
A plugin is usually a npm package, so you install them like other npm packages using npm.
```bash npm2yarn
npm install --save docusaurus-plugin-name
```
Then you add it in your site's `docusaurus.config.js`'s `plugins` option:
```jsx {3} title="docusaurus.config.js"
module.exports = {
// ...
plugins: ['@docusaurus/plugin-content-pages'],
};
```
Docusaurus can also load plugins from your local directory, you can do something like the following:
```jsx {5} title="docusaurus.config.js"
const path = require('path');
module.exports = {
// ...
plugins: [path.resolve(__dirname, '/path/to/docusaurus-local-plugin')],
};
```
## Configuring plugins
For the most basic usage of plugins, you can provide just the plugin name or the absolute path to the plugin.
However, plugins can have options specified by wrapping the name and an options object in an array inside your config. This style is usually called `Babel Style`.
```js {4-9} title="docusaurus.config.js"
module.exports = {
// ...
plugins: [
[
'@docusaurus/plugin-xxx',
{
/* options */
},
],
],
};
```
Example:
```js title="docusaurus.config.js"
module.exports = {
plugins: [
// Basic usage.
'@docusaurus/plugin-google-analytics',
// With options object (babel style)
[
'@docusaurus/plugin-sitemap',
{
cacheTime: 600 * 1000,
},
],
],
};
```
## Plugins 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 not limited to) extending the webpack config, modifying the data being loaded and creating new components to be used in a page.
## Creating plugins
A plugin is a module which exports a function that takes two parameters and returns an object when executed.
### Module definition
The exported modules for plugins are called with two parameters: `context` and `options` and returns a JavaScript object with defining the [lifecycle APIs](./lifecycle-apis.md).
```js title="docusaurus.config.js"
module.exports = function(context, options) {
// ...
return {
name: 'my-docusaurus-plugin',
async loadContent() { ... },
async contentLoaded({content, actions}) { ... },
/* other lifecycle API */
};
};
```
#### `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:
```js
interface LoadContext {
siteDir: string;
generatedFilesDir: string;
siteConfig: DocusaurusConfig;
outDir: string;
baseUrl: string;
}
```
#### `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`. Alternatively, if preset contains the plugin, the preset will then be in charge of passing the correct options into the plugin. It is up to individual plugin to define what options it takes.
#### Return value
The returned object value should implement the [lifecycle APIs](lifecycle-apis.md).
## Official plugins
Find the list of official Docusaurus plugins [here](https://github.com/facebook/docusaurus/tree/master/packages).
### `@docusaurus/plugin-content-blog`
Provides the [Blog](blog.md) feature and is the default blog plugin for Docusaurus.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-content-blog
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. You can also configure it through the [classic preset options](presets.md#docusauruspreset-classic) instead of doing it like below.
:::
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-blog',
{
/**
* Path to data on filesystem relative to site dir.
*/
path: 'blog',
/**
* URL for editing a blog post.
* Example: 'https://github.com/facebook/docusaurus/edit/master/website/blog/'
*/
editUrl:
'https://github.com/facebook/docusaurus/edit/master/website/blog/',
/**
* URL route for the blog section of your site.
* *DO NOT* include a trailing slash.
*/
routeBasePath: 'blog',
include: ['*.md', '*.mdx'],
postsPerPage: 10,
/**
* Theme components used by the blog pages.
*/
blogListComponent: '@theme/BlogListPage',
blogPostComponent: '@theme/BlogPostPage',
blogTagsListComponent: '@theme/BlogTagsListPage',
blogTagsPostsComponent: '@theme/BlogTagsPostsPage',
/**
* Remark and Rehype plugins passed to MDX.
*/
remarkPlugins: [
/* require('remark-math') */
],
rehypePlugins: [],
/**
* Custom Remark and Rehype plugins passed to MDX before
* the default Docusaurus Remark and Rehype plugins.
*/
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
/**
* Truncate marker, can be a regex or string.
*/
truncateMarker: /<!--\s*(truncate)\s*-->/,
/**
* Show estimated reading time for the blog post.
*/
showReadingTime: true,
/**
* Blog feed.
* If feedOptions is undefined, no rss feed will be generated.
*/
feedOptions: {
type: '', // required. 'rss' | 'feed' | 'all'
title: '', // default to siteConfig.title
description: '', // default to `${siteConfig.title} Blog`
copyright: '',
language: undefined, // possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
},
},
],
],
};
```
### `@docusaurus/plugin-content-docs`
Provides the [Docs](markdown-features.mdx) functionality and is the default docs plugin for Docusaurus.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-content-docs
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. You can also configure it through the [classic preset options](presets.md#docusauruspreset-classic) instead of doing it like below.
:::
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
/**
* Path to data on filesystem relative to site dir.
*/
path: 'docs',
/**
* URL for editing a doc in the website repo.
* Example: 'https://github.com/facebook/docusaurus/edit/master/website/'
*/
editUrl: 'https://github.com/facebook/docusaurus/edit/master/website/',
/**
* URL route for the blog section of your site.
* *DO NOT* include a trailing slash.
*/
routeBasePath: 'docs',
homePageId: '_index', // Document id for docs home page.
include: ['**/*.md', '**/*.mdx'], // Extensions to include.
/**
* Path to sidebar configuration for showing a list of markdown pages.
* Warning: will change
*/
sidebarPath: '',
/**
* Theme components used by the docs pages
*/
docLayoutComponent: '@theme/DocPage',
docItemComponent: '@theme/DocItem',
/**
* Remark and Rehype plugins passed to MDX
*/
remarkPlugins: [
/* require('remark-math') */
],
rehypePlugins: [],
/**
* Custom Remark and Rehype plugins passed to MDX before
* the default Docusaurus Remark and Rehype plugins.
*/
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
/**
* Whether to display the author who last updated the doc.
*/
showLastUpdateAuthor: false,
/**
* Whether to display the last date the doc was updated.
*/
showLastUpdateTime: false,
},
],
],
};
```
### `@docusaurus/plugin-content-pages`
The default pages plugin for Docusaurus. The classic template ships with this plugin with default configurations. This plugin provides [creating pages](creating-pages.md) functionality.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-content-pages
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. You can also configure it through the [classic preset options](presets.md#docusauruspreset-classic) instead of doing it like below.
:::
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docuaurus/plugin-content-pages',
{
/**
* Path to data on filesystem
* relative to site dir
* components in this directory will be automatically converted to pages
*/
path: 'src/pages',
/**
* URL route for the blog section of your site
* do not include trailing slash
*/
routeBasePath: '',
include: ['**/*.{js,jsx}'],
},
],
],
};
```
### `@docusaurus/plugin-google-analytics`
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.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-google-analytics
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency.
:::
**Configuration**
```js title="docusaurus.config.js"
module.exports = {
plugins: ['@docusaurus/plugin-google-analytics'],
themeConfig: {
googleAnalytics: {
trackingID: 'UA-141789564-1',
// Optional fields.
anonymizeIP: true, // Should IPs be anonymized?
},
},
};
```
### `@docusaurus/plugin-google-gtag`
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.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-google-gtag
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency.
:::
**Configuration**
```js title="docusaurus.config.js"
module.exports = {
plugins: ['@docusaurus/plugin-google-gtag'],
themeConfig: {
gtag: {
trackingID: 'UA-141789564-1',
// Optional fields.
anonymizeIP: true, // Should IPs be anonymized?
},
},
};
```
### `@docusaurus/plugin-sitemap`
This plugin creates sitemap for your site so that search engine crawlers can crawl your site more accurately.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-sitemap
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. You can also configure it through the [classic preset options](presets.md#docusauruspreset-classic) instead of doing it like below.
:::
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-sitemap',
{
cacheTime: 600 * 1000, // 600 sec - cache purge period
changefreq: 'weekly',
priority: 0.5,
},
],
],
};
```
### `@docusaurus/plugin-ideal-image`
Docusaurus Plugin to generate an almost ideal image (responsive, lazy-loading, and low quality placeholder) **in the production builds**.
```bash npm2yarn
npm install --save @docusaurus/plugin-ideal-image
```
Modify your `docusaurus.config.js`
```diff
module.exports = {
...
+ plugins: ['@docusaurus/plugin-ideal-image'],
...
}
```
#### Usage
This plugin supports the PNG, GIF 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')} />
```
#### Options
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | `ideal-img/[name].[hash:hex:7].[width].[ext]` | Filename template for output files. |
| `sizes` | `array` | _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` | `integer` | _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` | `integer` | | As an alternative to manually specifying `sizes`, you can specify `min`, `max` and `steps`, and the sizes will be generated for you. |
| `max` | `integer` | | See `min` above |
| `steps` | `integer` | `4` | Configure the number of images generated between `min` and `max` (inclusive) |
| `quality` | `integer` | `85` | JPEG compression quality |

View file

@ -0,0 +1,197 @@
---
id: using-themes
title: Themes
---
Like plugins, themes are designed to add functionality to your Docusaurus site. As a good rule of thumb, themes are mostly focused on client-side, where plugins are more focused on server-side functionalities. Themes are also designed to be replace-able with other themes.
## Using themes
To use themes, specify the themes in your `docusaurus.config.js`. You may use multiple themes:
```js {3} title="docusaurus.config.js"
module.exports = {
// ...
themes: ['@docusaurus/theme-classic', '@docusaurus/theme-live-codeblock'],
};
```
## Theme components
Most of the time, theme is used to provide a set of React components, e.g. `Navbar`, `Layout`, `Footer`.
Users can use these components in their code 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.
1. A Docusaurus theme packages's `theme` directory.
1. Fallback components provided by Docusaurus core (usually not needed).
Given the following structure
```
website
├── node_modules
│ └── docusaurus-theme
│ └── 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. In iOS, method swizzling is the process of changing the implementation of an existing selector (method). In the context of a website, component swizzling means providing an alternative component that takes precedence over the component provided by the theme.
**Themes are for providing UI components to present 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, so it makes it easy to swap out the themes for other designs (i.e., Bootstrap).
For example, a Docusaurus blog consists of a blog plugin and a blog theme.
```js title="docusaurus.config.js"
{
theme: ['theme-blog'],
plugins: ['plugin-content-blog'],
}
```
And if you want to use Bootstrap styling, you can swap out the theme with `theme-blog-bootstrap` (fictitious non-existing theme):
```js title="docusaurus.config.js"
{
theme: ['theme-blog-bootstrap'],
plugins: ['plugin-content-blog'],
}
```
The content plugin remains the same and the only thing you need to change is the theme.
## Swizzling theme components
:::caution
We would like to discourage swizzling of components until we've minimally reached a Beta stage. The components APIs have been changing rapidly and are likely to keep changing until we reach Beta. Stick with the default appearance for now if possible to save yourself some potential pain in future.
:::
Docusaurus Themes' components are designed to be replaceable. To make it easier for you, we created a command for you to replace theme components called `swizzle`.
To swizzle a component for a theme, run the following command in your doc site:
```shell
docusaurus swizzle <theme name> [component name]
```
As an example, to swizzle the `<Footer />` component in `@docusaurus/theme-classic` for your site, run:
```bash npm2yarn
npm run swizzle @docusaurus/theme-classic Footer
```
This will copy the current `<Footer />` component used by the theme to a `src/theme/Footer` directory under the root of your site, which is where Docusaurus will look for swizzled components. Docusaurus will then use swizzled component in place of the original one from the theme.
Although we highly discourage swizzling of all components, if you wish to do that, run:
```bash npm2yarn
npm run swizzle @docusaurus/theme-classic
```
**Note**: You need to restart your webpack dev server in order for Docusaurus to know about the new component.
## Official themes by Docusaurus
### `@docusaurus/theme-classic`
The classic theme for Docusaurus. You can refer to [classic theme configuration](theme-classic.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.
:::
### `@docusaurus/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` path with OpenSearch support.
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency.
:::
### `@docusaurus/theme-live-codeblock`
This theme provides a `@theme/CodeBlock` component that is powered by react-live. You can read more on [interactive code editor](markdown-features.mdx#interactive-code-editor) documentation.
```bash npm2yarn
npm install --save @docusaurus/theme-live-codeblock
```
## Themes design
While themes share the exact same lifecycle methods with plugins, their 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. So a typical theme implementation would look like a `src/index.js` file that hooks it up to the lifecycle methods. Most likely they would not use `loadContent`, which plugins would use. And it is typically accompanied by a `src/theme` directory full of components.
To summarize:
- Themes share the same lifecycle methods with Plugins
- Themes are run after all existing Plugins
- Themes exist to add component aliases by extending the webpack config
## Writing customized Docusaurus themes
A Docusaurus theme normally includes an `index.js` file where you hook up to the lifecycle methods, alongside with a `theme/` directory of components. A typical Docusaurus `theme` folder looks like this:
```shell {5-7}
website
├── package.json
└── src
├── index.js
└── theme
├── MyThemeComponent
└── AnotherThemeComponent.js
```
There are two lifecycle methods that are essential to theme implementation:
- [`getThemePath()`](lifecycle-apis.md#getthemepath)
- [`getClientModules()`](lifecycle-apis.md#getclientmodules)
<!--
Outline
---
High-level overview about themes:
- how to use a theme
- how to pass theme configurations
- how to swizzle components and the power of it
Related pieces
---
- [Advanced Guides Themes](advanced-themes.md)
- [Lifecycle APIs](lifecycle-apis.md)
References
---
- [themes RFC](https://github.com/facebook/docusaurus/issues/1438)
- [how classic template uses themes](/packages/docusaurus/templates/classic/docusaurus.config.js)
- [using plugins doc](using-plugins.md)
- [vuepress docs on themes](https://v1.vuepress.vuejs.org/theme/)
-->

View file

@ -0,0 +1,158 @@
---
id: versioning
title: Versioning
---
You can use the version script 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 changes moving forward.
:::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.
## Directory structure
```shell
website
├── sidebars.json # sidebar for master (next) version
├── docs # docs directory for master (next) 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 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` | next | /docs/next/hello |
### Tagging a new version
1. First, make sure your content in the `docs` directory is ready to be frozen as a version. A version always should be based from master.
1. 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-<version>/` folder.
- Create a versioned sidebars file based from your current [sidebar](sidebar.md) configuration (if it exists) - saved as `versioned_sidebars/version-<version>-sidebars.json`.
- Append the new version number to `versions.json`.
## Files
### Creating new files
1. Place the new file into the corresponding version folder.
1. Include the reference for the new file into the corresponding sidebar file, according to version number.
**Master docs**
```shell
# The new file.
docs/new.md
# Edit the corresponding sidebar file.
sidebar.js
```
**Older docs**
```shell
# The new file.
versioned_docs/version-1.0.0/new.md
# Edit the corresponding sidebar file.
versioned_sidebars/version-1.0.0-sidebars.json
```
### Linking files
- Remember to include the `.md` extension.
- Files will be linked to correct corresponding version.
- Relative paths work as well.
```md
The [@hello](hello.md#paginate) document is great!
See the [Tutorial](../getting-started/tutorial.md) for more info.
```
## Versions
Each directory in `versioned_docs/` will represent a documentation 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.
1. Commit and push changes.
1. 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
You can delete/remove versions as well.
1. Remove the version from `versions.json`.
Example:
```diff {4}
[
"2.0.0",
"1.9.0",
- "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`.
## Recommended practices
### Version your documentation only when needed
For example, you are building a 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
As a good rule of thumb, try to keep the number of your versions below 10. **It is very likely** that you will have a lot of obsolete versioned documentation that nobody even reads anymore. For example, [Jest](https://jestjs.io/versions) is currently in version `24.9`, and only maintains several latest documentation version with the lowest being `22.X`. Keep it small 😊
### 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';
```

View file

@ -0,0 +1,156 @@
{
"version-2.0.0-alpha.56/docs": [
{
"type": "category",
"label": "Docusaurus",
"items": [
{
"type": "doc",
"id": "version-2.0.0-alpha.56/introduction"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/design-principles"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/contributing"
}
]
},
{
"type": "category",
"label": "Getting Started",
"items": [
{
"type": "doc",
"id": "version-2.0.0-alpha.56/installation"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/configuration"
}
]
},
{
"type": "category",
"label": "Guides",
"items": [
{
"type": "doc",
"id": "version-2.0.0-alpha.56/creating-pages"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/styling-layout"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/static-assets"
},
{
"type": "category",
"label": "Docs",
"items": [
{
"type": "doc",
"id": "version-2.0.0-alpha.56/docs-introduction"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/markdown-features"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/versioning"
}
]
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/blog"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/search"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/deployment"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/migrating-from-v1-to-v2"
}
]
},
{
"type": "category",
"label": "Advanced Guides",
"items": [
{
"type": "doc",
"id": "version-2.0.0-alpha.56/using-plugins"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/using-themes"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/presets"
}
]
},
{
"type": "category",
"label": "API Reference",
"items": [
{
"type": "doc",
"id": "version-2.0.0-alpha.56/cli"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/docusaurus-core"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/docusaurus.config.js"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/lifecycle-apis"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/theme-classic"
}
]
}
],
"version-2.0.0-alpha.56/community": [
{
"type": "doc",
"id": "version-2.0.0-alpha.56/support"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/team"
},
{
"type": "doc",
"id": "version-2.0.0-alpha.56/resources"
},
{
"type": "link",
"href": "/showcase",
"label": "Showcase"
},
{
"type": "link",
"href": "/feedback",
"label": "Feedback"
}
]
}

View file

@ -1,4 +1,5 @@
[
"2.0.0-alpha.56",
"2.0.0-alpha.55",
"2.0.0-alpha.54",
"2.0.0-alpha.50",