docs(v2): delete alpha.43

This commit is contained in:
Alexey Pyltsyn 2020-05-28 08:58:04 +03:00
parent 07b9e9cd62
commit 0047db2896
25 changed files with 1 additions and 4802 deletions

View file

@ -1,162 +0,0 @@
---
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
links: [
...
{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
authorURL: https://github.com/JoelMarcey
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.
## 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 {9-12}
// 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.
**Note:** Make sure there's no `index.js` page in `src/pages` or else there will be two files mapping to the same route!
```js {10}
// docusaurus.config.js
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
path: './blog',
routeBasePath: '/', // Set this value to '/'.
},
},
],
],
};
```
<!--
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

@ -1,88 +0,0 @@
---
id: cli
title: CLI
---
Docusaurus provides a set of scripts to help you generate, serve, and deploy your website.
Once your website is generated, your website package will contain the Docusaurus scripts that you may invoke with your package manager:
```json
// 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 the static site with [Webpack Dev Server](https://webpack.js.org/configuration/dev-server).
**options**
| Options | Default | Description |
| --- | --- | --- |
| `--port` | `3000` | Specifies the port of the dev server |
| `--host` | `localhost` | Specify a host to use. E.g., 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. |
### `docusaurus build`
Compiles your site for production.
**options**
| Options | Default | Description |
| --- | --- | --- |
| `--bundle-analyzer` | | Analyze your bundle with [bundle analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer) |
### `docusaurus swizzle`
> ⚠️ 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.
Swizzle any Docusaurus Theme components with your own component with `docusaurus swizzle`.
```shell
docusaurus swizzle <themeName> [componentName] [siteDir]
```
**params**
- `themeName`: name of the theme you are using
- `swizzleComponent`: name of the component to be swizzled
Running the above 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.
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/).

View file

@ -1,145 +0,0 @@
---
id: configuration
title: Configuration
---
Docusaurus has a unique take on configurations. We encourage you to congregate information of your site into one place. We will 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 fields.
## What goes into `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` at root that includes the necessary data for the initial site.
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 Docusaurus' `deploy` command.
It is recommended to check the [deployment docs](deployment.md) for more information.
### Theme, plugin, and preset configurations
List the installed [themes](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
// 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
// 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
// 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
//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 a custom field, define it on `customFields`
Example:
```js {3-6}
// docusaurus.config.js
module.exports = {
customFields: {
image: '',
keywords: [],
},
};
```
## 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 {2,5-6}
import React from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
const Hello = () => {
const context = useDocusaurusContext();
const {siteConfig = {}} = context;
const {title, tagline} = siteConfig;
return <div>{`${title} · ${tagline}`}</div>;
};
```
> 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

@ -1,190 +0,0 @@
---
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

@ -1,79 +0,0 @@
---
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.
## 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
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.
## 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 e.g. 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
.
```
## 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

@ -1,148 +0,0 @@
---
id: deployment
title: Deployment
---
To build the static files of your website for production, run:
```bash npm2yarn
npm run build
```
Once it finishes, you should see the production build under 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/), and [Render](https://render.com/static-sites). Docusaurus sites are statically rendered so they work without JavaScript too!
## 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 seconds:
1. First, install their [command-line interface](https://zeit.co/download):
```bash
npm i -g now
```
2. 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 GitHub Pages
Docusaurus provides a easy way to publish to GitHub Pages.
### `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}
module.exports = {
...
url: 'https://endiliey.github.io', // Your website URL
baseUrl: '/',
projectName: 'endiliey.github.io',
organizationName: 'endiliey'
...
}
```
### 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. |
| `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"
```
<!--
TODO: Talk about deployment steps and different hosting options.
References:
- https://www.gatsbyjs.org/docs/deploying-and-hosting/
-->
## 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 {3-4}
// 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`.
## 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 deploys 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.
2. Select the branch to deploy. The default is `master`.
3. 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.

View file

@ -1,30 +0,0 @@
---
id: design-principles
title: Design Principles
---
> :warning: _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

@ -1,161 +0,0 @@
---
id: docusaurus-core
title: Docusaurus Client API
sidebar_label: Client API
---
Docusaurus provides some API on client that can be helpful when building your site.
## `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 `<NavLink>` component that adds useful enhancements specific to Docusaurus. All props are passed through to react-routers `<NavLink>` 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. */}
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" />
```
### `activeClassName`: string
The class to give the `<Link>` when it is active. The default given class is `active`. This will be joined with the `className` prop.
```jsx {1}
<Link to="/faq" activeClassName="selected">
FAQs
</Link>
```
## `useDocusaurusContext`
React Hooks 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 baseUrl.
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>
);
}
```
## `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" />;
}
```

View file

@ -1,304 +0,0 @@
---
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
// docusaurus.config.js
module.exports = {
title: 'Docusaurus',
};
```
### `tagline`
- Type: `string`
The tagline for your website.
```js
// docusaurus.config.js
module.exports = {
tagline:
'Docusaurus makes it easy to maintain Open Source documentation websites.',
};
```
### `favicon`
- Type: `string`
URL for site favicon. Example:
```js
// 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
// 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
// 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
// docusaurus.config.js
module.exports = {
baseUrl: '/',
};
```
## Optional fields
### `organizationName`
- Type: `string`
The GitHub user or organization that owns the repository. Used by the deployment command.
```js
// docusaurus.config.js
module.exports = {
// Docusaurus's organization is facebook
organizationName: 'facebook',
};
```
### `projectName`
- Type: `string`
The name of the GitHub repository. Used by the deployment command.
```js
// docusaurus.config.js
module.exports = {
projectName: 'docusaurus',
};
```
### `githubHost`
- Type: `string`
The hostname of your server. Useful if you are using GitHub Enterprise.
```js
// 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
// docusaurus.config.js
module.exports = {
themeConfig: {
navbar: {
title: 'Site Title',
logo: {
alt: 'Site Logo',
src: 'img/logo.svg',
},
links: [
{
to: 'docs/docusaurus.config.js',
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.`,
},
},
};
```
### `plugins`
<!-- TODO: configuration for plugins -->
- Type: `any[]`
```js
// docusaurus.config.js
module.exports = {
plugins: [],
};
```
### `themes`
<!-- TODO: configuration for plugins -->
- Type: `any[]`
```js
// docusaurus.config.js
module.exports = {
themes: [],
};
```
### `presets`
<!-- TODO: configuration for presets -->
- Type: `any[]`
```js
// 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`
```jsx
// 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
// 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
// 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

@ -1,102 +0,0 @@
---
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.9.0 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.
**Important Note:** 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
├── package.json
├── 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.
## 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

@ -1,112 +0,0 @@
---
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.
---
import useBaseUrl from '@docusaurus/useBaseUrl';
## :warning: Disclaimer
This is an **early and alpha release** of Docusaurus 2. We are making it available early to maximize community participation and feedback. Expect it to evolve a lot over the course of the alpha-beta period. If you are adventurous enough to be an early adopter, 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 provide feedback to make sure it suits your needs
- :white_check_mark: You are curious about what's next as a Docusaurus user
**Do not use this if**
- :x: You need a full production-ready solution (<small>try [Docusaurus 1](https://docusaurus.io/) instead</small>)
- :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 alpha period
- :x: You need support for IE11
## A better Docusaurus is coming to town
<img alt="Docusaurus " src={useBaseUrl('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 most content-driven websites (e.g. Documentation, Blogs, Product Landing and Marketing Pages, etc) extremely fast.
While our main focus will still be helping you get your documentations right and well, the shared nature of building this static site generator makes it possible for you to build your whole website interface one-stop.
## 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
- 🌍 **i18n** (_coming soon_)
- 💾 **Document Versioning** Helps you keep documentation in sync with project releases.
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 slate 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 doc site. As a result, many have to turn 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 based on `<script />` tags, Docusaurus sites are React apps. With tooling of our current ecosystem, 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 wanted 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

@ -1,431 +0,0 @@
---
id: lifecycle-apis
title: Lifecycle APIs
---
> :warning: _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 {6-8}
// 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 {6-7}
// 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).
### `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
// 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 {5-20}
// 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 {5-12}
// 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 {5-10}
// 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 {5-12}
// 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 {5-29}
// 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 {7-9}
// 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 {8-10}
// 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}) {
// contentLoaded hook is done after loadContent hook is done
// actions are set of functional API provided by Docusaurus. e.g: addRoute
},
async postBuild(props) {
// after docusaurus <build> finish
},
// TODO
async postStart(props) {
// docusaurus <start> finish
},
// TODO
afterDevServer(app, server) {
// https://webpack.js.org/configuration/dev-server/#devserverbefore
},
// TODO
beforeDevServer(app, server) {
// https://webpack.js.org/configuration/dev-server/#devserverafter
},
configureWebpack(config, isServer) {
// 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() {
// Path 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

@ -1,488 +0,0 @@
---
id: markdown-features
title: Markdown Features
description: Docusaurus uses GitHub Flavored Markdown (GFM). Find out more about Docusaurus-specific features when writing Markdown.
---
<!--
combining:
- assets
- markdown features
-->
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`.
:::
---
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. -->
In the top of the file, specify `id` the `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
---
```
### Embedding React components
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.
### Referencing other documents
If you want to reference another document file, you should 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.
### 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}
// 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), install the `prismjs` npm package, then swizzle the `CodeBlock` component and add the desired language(s) there.
For example, if you want to add highlighting for the `powershell` language:
```js
// src/theme/CodeBlock/index.js
import Prism from 'prism-react-renderer/prism';
(typeof global !== 'undefined' ? global : window).Prism = Prism;
require('prismjs/components/prism-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
/* /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;
```
### 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.
### 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:
```markdown
:::tip Title
The content and title *can* include markdown.
:::
```
:::tip Title
The content and title *can* include markdown.
:::

View file

@ -1,694 +0,0 @@
---
id: migrating-from-v1-to-v2
title: Migrating from v1 to v2
---
import ColorGenerator from '@site/src/components/ColorGenerator';
This doc guides you through migrating an existing Docusaurus 1 site to Docusaurus 2.
**Note: This migration guide is targeted at Docusaurus users without translation and/or versioning features and assumes 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:
```json
// package.json
{
dependencies: {
- "docusaurus": "^1.x.x",
+ "@docusaurus/core": "^2.0.0-alpha.48",
+ "@docusaurus/preset-classic": "^2.0.0-alpha.48",
}
}
```
#### 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}
{
"scripts": {
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy"
...
}
}
```
A typical Docusaurus 2 `package.json` may look like this:
```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:
```
# 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
// 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 {8-10}
// 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
/**
* /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
// 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.`,
},
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
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 {7-20}
// 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 {5-9}
// 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 {9}
// 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 {9-22}
// 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 {6}
// docusaurus.config.js
module.exports = {
// ...
themeConfig: {
googleAnalytics: {
trackingID: 'UA-141789564-1',
},
// ...
},
};
```
#### `gaGtag`
```jsx {6}
// 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](sidebar.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`.
```js
{
- 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.
### Frontmatter
The Docusaurus frontmatter 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
> :warning: _This section 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 reasoning on v1's problem
### Migrate your versioned_docs frontmatter
- 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.
Example, 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:
```yaml {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.
Example, Docusaurus 1 can't differentiate `docs/xxx.md`
```md
---
id: version-1.0.0-hello
---
Another content
```
and `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`:
```json {2-3,5-6,9-10}
{
+ "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 & versioned_docs
In v2, we use snapshot approach on 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
// 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 & 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

@ -1,145 +0,0 @@
---
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 {4}
// docusaurus.config.js
module.exports = {
// ...
presets: ['@docusaurus/preset-xxxx'],
};
```
To load presets from your local directory, specify how to resolve them:
```jsx {6}
// 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: ['@docusaurus/themes-cool', '@docusaurus/themes-bootstrap'],
plugins: ['@docusaurus/plugin-blog'],
};
};
```
then in your Docusaurus config, you may configure the preset instead:
```jsx {4}
// docusaurus.config.js
module.exports = {
// ...
presets: ['@docusaurus/preset-a'],
};
```
This is equivalent of doing:
```jsx
// 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
// 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
// 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

@ -1,52 +0,0 @@
---
id: search
title: Search
keywords:
- algolia
- search
---
Docusaurus's 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://community.algolia.com/docsearch/).
```jsx {4-9}
// docusaurus.config.js
themeConfig: {
// ....
algolia: {
appId: 'app-id',
apiKey: 'api-key',
indexName: 'index-name',
algoliaOptions: {}, // Optional, if provided by Algolia
},
},
```
### 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

@ -1,244 +0,0 @@
---
id: sidebar
title: 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 {9-10}
// 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
// sidebars.js
module.exports = {
docs: {
'Getting started': ['greeting'],
Docusaurus: ['doc1'],
},
};
```
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.
```js
// 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
// sidebars.js
module.exports = {
firstSidebar: {
'Category A': ['doc1'],
},
secondSidebar: {
'Category A': ['doc2'],
'Category B': ['doc3'],
},
};
```
## 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 frontmatter. For example, if `guide/hello.md` content is defined as below, it's final `id` is `guide/part1`.
```yml
---
id: part1
---
Lorem ipsum
```
## 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
// 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', // string - the label that should be displayed.
href: 'https://example.com' // string - the target URL.
}
```
### 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', // string - document id
}
```
### 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
// sidebars.js
module.exports = {
docs: {
Guides: [
'creating-pages',
{
type: 'category',
label: 'Docs',
items: ['markdown-features', 'sidebar'],
},
],
},
};
```
### 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 {5}
// docusaurus.config.js
module.exports = {
...
themeConfig: {
sidebarCollapsible: false,
...
},
}
```

View file

@ -1,59 +0,0 @@
---
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
// MyComponent.js
import useBaseUrl from '@docusaurus/useBaseUrl';
<img
alt="Docusaurus with Keytar"
src={useBaseUrl('img/docusaurus_keytar.svg')}
/>;
```
### 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.
```txt
// my-doc.mdx
---
id: my-doc
title: My Doc
---
import useBaseUrl from '@docusaurus/useBaseUrl'; // Add to the top of the file below the front matter.
...
<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
// 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

@ -1,129 +0,0 @@
---
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 {8-10}
// docusaurus.config.js
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
};
```
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
/**
* /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
/* /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
/* 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
> :warning: _This section is a work in progress._ [Welcoming PRs](https://github.com/facebook/docusaurus/issues/1640).\_

View file

@ -1,151 +0,0 @@
---
id: theme-classic
title: '@docusaurus/theme-classic'
---
> :warning: _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
// docusaurus.config.js
module.exports = {
...
themeConfig: {
disableDarkMode: false,
...
},
};
```
### Meta image
You can configure a default image that will be used for your meta tag, in particular `og:image` and `twitter:image`.
```js
// 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',
...
},
}
```
## 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. You can also set a different logo for dark mode.
```js
// 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
},
},
...
},
}
```
### Navbar Links
You can add links to the navbar via `themeConfig.navbar.links`:
```js
// docusaurus/config.js
module.exports = {
...
themeConfig: {
navbar: {
links: [
{
to: 'docs/docusaurus.config.js',
label: 'docusaurus.config.js',
position: 'left',
},
// ... other links
],
},
...
},
}
```
Outbound links automatically get `target="_blank" rel="noopener noreferrer"`.
### 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
// docusaurus/config.js
module.exports = {
...
themeConfig: {
navbar: {
hideOnScroll: true,
},
...
},
}
```
## Footer
## `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}
// 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
// docusaurus/config.js
module.exports = {
...
themeConfig: {
prism: {
defaultLanguage: 'javascript',
},
...
},
};
```

View file

@ -1,419 +0,0 @@
---
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 {4}
// 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 {6}
// 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 {5-10}
// docusaurus.config.js
module.exports = {
// ...
plugins: [
[
'@docusaurus/plugin-xxx',
{
/* options */
},
],
],
};
```
Example:
```js
// 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
// my-docusaurus-plugin.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
```
> 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
// docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-blog',
{
/**
* Path to data on filesystem
* relative to site dir
*/
path: 'blog',
/**
* URL route for the blog section of your site
* do not include 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: [],
rehypePlugins: [],
/**
* Truncate marker, can be a regex or string.
*/
truncateMarker: /<!--\s*(truncate)\s*-->/
/**
* 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
```
> 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
// docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
/**
* Path to data on filesystem
* relative to site dir
*/
path: 'docs',
/**
* URL for editing 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 trailing slash
*/
routeBasePath: 'docs',
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: [],
rehypePlugins: [],
/**
* 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
```
> 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
// 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
```
> If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency.
**Configuration**
```js
// 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
```
> If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency.
**Configuration**
```js
// 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
```
> 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
// 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)
```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 png, gif and jpg 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

@ -1,180 +0,0 @@
---
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 {4}
// 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
// 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
// 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
> ⚠️ 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.
**Note**: You need to restart your dev server for Docusaurus to pick up 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
```
> 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
```
> 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

@ -1,155 +0,0 @@
---
title: Versioning
---
You can use the version script to cut 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.
## :warning: Disclaimer
> Consider it really well before starting to version your documentation.
Most of the times, you don't need versioning and it will just increase your build time and introduces complexity to your codebase. Versioning is **best suited for website with high-traffic and rapid changes in documentation between version**. If your documentation rarely changes, don't version.
To better understand how versioning works and see if it suits your needs, you can read up 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 it as `versioned_sidebars/version-<version>-sidebars.json`.
- Append the new version number into `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

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

View file

@ -3,6 +3,5 @@
"2.0.0-alpha.55", "2.0.0-alpha.55",
"2.0.0-alpha.54", "2.0.0-alpha.54",
"2.0.0-alpha.50", "2.0.0-alpha.50",
"2.0.0-alpha.48", "2.0.0-alpha.48"
"2.0.0-alpha.43"
] ]