chore(v2): prepare v2.0.0.alpha-62 release (#3359)

* Add alpha 62

* v2.0.0-alpha.62
This commit is contained in:
Sébastien Lorber 2020-08-28 19:17:56 +02:00 committed by GitHub
parent ae877f2990
commit 4f448bd54b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
67 changed files with 7987 additions and 100 deletions

View file

@ -1,5 +1,197 @@
# Docusaurus 2 Changelog
## 2.0.0-alpha.62 (2020-08-28)
#### :rocket: New Feature
- `docusaurus-plugin-content-docs`, `docusaurus-theme-classic`
- [#3357](https://github.com/facebook/docusaurus/pull/3357) feat(v2): docs version configuration: lastVersion, version.{path,label} ([@slorber](https://github.com/slorber))
- [#3328](https://github.com/facebook/docusaurus/pull/3328) feat(v2): Provide docs plugin theme typing ([@SamChou19815](https://github.com/SamChou19815))
- `docusaurus-theme-classic`
- [#3356](https://github.com/facebook/docusaurus/pull/3356) feat(v2): Provide type definitions for remaining theme-classic components ([@SamChou19815](https://github.com/SamChou19815))
- [#3274](https://github.com/facebook/docusaurus/pull/3274) feat(v2): add TOC to blog posts ([@amy-lei](https://github.com/amy-lei))
- `docusaurus-plugin-content-pages`, `docusaurus-theme-classic`
- [#3354](https://github.com/facebook/docusaurus/pull/3354) feat(v2): Provide type definitions for MDXPage from page plugin ([@SamChou19815](https://github.com/SamChou19815))
- `docusaurus-plugin-content-blog`, `docusaurus-plugin-content-docs`, `docusaurus-theme-classic`
- [#3348](https://github.com/facebook/docusaurus/pull/3348) feat(v2): Provide typing to most of the theme-classic components ([@SamChou19815](https://github.com/SamChou19815))
- `docusaurus-init`, `docusaurus-plugin-content-blog`
- [#3284](https://github.com/facebook/docusaurus/pull/3284) feat(v2): blog slug frontmatter ([@JeanMarcSaad](https://github.com/JeanMarcSaad))
- `docusaurus-init`, `docusaurus-theme-bootstrap`
- [#2981](https://github.com/facebook/docusaurus/pull/2981) feat(v2): bootstrap theme, preset, template, CI previews ([@fanny](https://github.com/fanny))
- `docusaurus-plugin-content-blog`, `docusaurus-theme-classic`
- [#3267](https://github.com/facebook/docusaurus/pull/3267) feat(v2): Provide blog plugin theme typing ([@SamChou19815](https://github.com/SamChou19815))
- `docusaurus-plugin-client-redirects`, `docusaurus-plugin-content-blog`, `docusaurus-plugin-debug`, `docusaurus-preset-classic`, `docusaurus-theme-bootstrap`, `docusaurus-types`, `docusaurus`
- [#3229](https://github.com/facebook/docusaurus/pull/3229) feat(v2): debug pages + debug layout + ability to debug content ([@slorber](https://github.com/slorber))
- `docusaurus-theme-classic`, `docusaurus-types`, `docusaurus`
- [#3021](https://github.com/facebook/docusaurus/pull/3021) feat(v2): update swizzle command to suggest component/theme ([@anshulrgoyal](https://github.com/anshulrgoyal))
- `docusaurus-mdx-loader`, `docusaurus-plugin-content-pages`
- [#3196](https://github.com/facebook/docusaurus/pull/3196) feat(v2): add support to ignore files in pages plugin ([@anshulrgoyal](https://github.com/anshulrgoyal))
- `docusaurus-plugin-content-blog`, `docusaurus-plugin-content-docs`, `docusaurus-plugin-content-pages`, `docusaurus-utils-validation`, `docusaurus`
- [#3204](https://github.com/facebook/docusaurus/pull/3204) feat(v2): blog + docs multi-instance plugins ([@slorber](https://github.com/slorber))
- `docusaurus-mdx-loader`
- [#3096](https://github.com/facebook/docusaurus/pull/3096) feat(v2): add support to import assets using relative link in markdown syntax ([@anshulrgoyal](https://github.com/anshulrgoyal))
#### :bug: Bug Fix
- `docusaurus-migrate`
- [#3358](https://github.com/facebook/docusaurus/pull/3358) fix(v2): fix migrate cli paths (sidebars/customcss) ([@slorber](https://github.com/slorber))
- `docusaurus`
- [#3311](https://github.com/facebook/docusaurus/pull/3311) fix(v2): add https support in webpack devserver ([@arcvats](https://github.com/arcvats))
- [#3313](https://github.com/facebook/docusaurus/pull/3313) fix(v2): resolve webpack loaders from siteDir/node_modules ([@anshulrgoyal](https://github.com/anshulrgoyal))
- [#3308](https://github.com/facebook/docusaurus/pull/3308) fix(v2): brokenLinks should not report links that belong to an existing folder if folder/index.html exists ([@slorber](https://github.com/slorber))
- [#3273](https://github.com/facebook/docusaurus/pull/3273) fix: logic error while deciding deploymentBranch ([@thehanimo](https://github.com/thehanimo))
- [#3281](https://github.com/facebook/docusaurus/pull/3281) fix(v2): allow swizzling of component even if case doesn't match ([@anshulrgoyal](https://github.com/anshulrgoyal))
- [#3222](https://github.com/facebook/docusaurus/pull/3222) fix(v2): update react-loadable-ssr-addon to solve yarn2 error ([@slorber](https://github.com/slorber))
- [#3191](https://github.com/facebook/docusaurus/pull/3191) fix(v2): add missing `lodash.flatmap` dependency ([@ylemkimon](https://github.com/ylemkimon))
- `docusaurus-plugin-content-blog`, `docusaurus-plugin-content-pages`, `docusaurus-plugin-ideal-image`, `docusaurus-plugin-pwa`, `docusaurus-theme-bootstrap`, `docusaurus-theme-search-algolia`, `docusaurus-types`
- [#3355](https://github.com/facebook/docusaurus/pull/3355) fix(v2): Add missing dependencies to packages ([@SamChou19815](https://github.com/SamChou19815))
- `docusaurus-theme-classic`
- [#3352](https://github.com/facebook/docusaurus/pull/3352) fix(v2): Allow the alt for the logo to be empty ([@Vinnl](https://github.com/Vinnl))
- [#3240](https://github.com/facebook/docusaurus/pull/3240) fix(v2): navbar dropdown opened with tab, not closing on click outside ([@Ako92](https://github.com/Ako92))
- `docusaurus-mdx-loader`, `docusaurus`
- [#3347](https://github.com/facebook/docusaurus/pull/3347) fix(v2): linking to asset or external html page -> don't use history.push() ([@slorber](https://github.com/slorber))
- `docusaurus-1.x`
- [#3340](https://github.com/facebook/docusaurus/pull/3340) fix(v1): show images after one line code block ([@adinaja](https://github.com/adinaja))
- `docusaurus-1.x`, `docusaurus`
- [#3290](https://github.com/facebook/docusaurus/pull/3290) fix(v1,v2): Add initial-scale=1.0 to all meta viewport tags ([@nebrelbug](https://github.com/nebrelbug))
- `docusaurus-theme-search-algolia`
- [#3297](https://github.com/facebook/docusaurus/pull/3297) fix(v2): keep DocSearch state on remounts ([@francoischalifour](https://github.com/francoischalifour))
- [#3280](https://github.com/facebook/docusaurus/pull/3280) fix(v2): allow search page swizzle ([@Ako92](https://github.com/Ako92))
- [#3263](https://github.com/facebook/docusaurus/pull/3263) fix(v2): do not index search pages ([@slorber](https://github.com/slorber))
- `docusaurus-mdx-loader`, `docusaurus-plugin-content-pages`
- [#3283](https://github.com/facebook/docusaurus/pull/3283) fix(v2): pass images in static dir to webpack-loader ([@anshulrgoyal](https://github.com/anshulrgoyal))
- Other
- [#3269](https://github.com/facebook/docusaurus/pull/3269) fix(v2): website feedback page hydration bug ([@mecm1993](https://github.com/mecm1993))
- [#3200](https://github.com/facebook/docusaurus/pull/3200) fix(v1): self-host user images ([@leoigel](https://github.com/leoigel))
- `docusaurus-plugin-google-gtag`
- [#3243](https://github.com/facebook/docusaurus/pull/3243) fix(v2): GTM, send page_view events on navigate ([@govardhan-srinivas](https://github.com/govardhan-srinivas))
- `docusaurus-plugin-content-docs`, `docusaurus-utils`
- [#3262](https://github.com/facebook/docusaurus/pull/3262) fix(v2): doc path special char (space or other) should lead to a valid slug ([@slorber](https://github.com/slorber))
- `docusaurus-plugin-content-blog`, `docusaurus-plugin-content-docs`, `docusaurus-utils-validation`, `docusaurus`
- [#3247](https://github.com/facebook/docusaurus/pull/3247) fix(v2): modify validation schema and tests for rehype/remark + remove duplicate dependency ([@teikjun](https://github.com/teikjun))
- `docusaurus-init`
- [#3258](https://github.com/facebook/docusaurus/pull/3258) fix(v2): fix template alt image prop ([@slorber](https://github.com/slorber))
- `docusaurus-plugin-content-blog`, `docusaurus-plugin-content-docs`, `docusaurus-theme-classic`, `docusaurus-utils-validation`, `docusaurus`
- [#3227](https://github.com/facebook/docusaurus/pull/3227) fix(v2): relax URI validation ([@anshulrgoyal](https://github.com/anshulrgoyal))
- `docusaurus-init`, `docusaurus-plugin-content-docs`
- [#3228](https://github.com/facebook/docusaurus/pull/3228) fix(v2): deprecate docs homePageId in favor of frontmatter "slug: /" ([@slorber](https://github.com/slorber))
- `docusaurus-plugin-content-docs`, `docusaurus`
- [#3225](https://github.com/facebook/docusaurus/pull/3225) fix(v2): swizzle minor improvements ([@slorber](https://github.com/slorber))
- `docusaurus-theme-classic`, `docusaurus-theme-live-codeblock`
- [#3210](https://github.com/facebook/docusaurus/pull/3210) fix(v2): fix theme validation for prism field and add tests ([@teikjun](https://github.com/teikjun))
- `docusaurus-plugin-content-docs`
- [#3192](https://github.com/facebook/docusaurus/pull/3192) fix(v2): add missing `chalk` and `lodash` dependencies ([@ylemkimon](https://github.com/ylemkimon))
#### :nail_care: Polish
- `docusaurus-module-type-aliases`, `docusaurus`
- [#3244](https://github.com/facebook/docusaurus/pull/3244) chore(v2): tighten up the TypeScript onboarding ([@orta](https://github.com/orta))
- `docusaurus-plugin-content-docs`, `docusaurus-theme-classic`, `docusaurus-utils`, `docusaurus`
- [#3245](https://github.com/facebook/docusaurus/pull/3245) refactor(v2): docs plugin refactor ([@slorber](https://github.com/slorber))
- `docusaurus`
- [#3188](https://github.com/facebook/docusaurus/pull/3188) fix(v2): Add a missing whitespace before prompt to use `npm run serve` ([@SamChou19815](https://github.com/SamChou19815))
#### :memo: Documentation
- Other
- [#3346](https://github.com/facebook/docusaurus/pull/3346) docs(v2): add draft doc ([@imskr](https://github.com/imskr))
- [#3336](https://github.com/facebook/docusaurus/pull/3336) docs(v2): add Nisarag to Fellows section ([@FocalChord](https://github.com/FocalChord))
- [#3335](https://github.com/facebook/docusaurus/pull/3335) docs(v2): update team profile ([@yangshun](https://github.com/yangshun))
- [#3334](https://github.com/facebook/docusaurus/pull/3334) docs(v2): add Drew to Fellows section ([@Drewbi](https://github.com/Drewbi))
- [#3333](https://github.com/facebook/docusaurus/pull/3333) docs(v2): add anshul and teikjun to fellows section of team page ([@teikjun](https://github.com/teikjun))
- [#3326](https://github.com/facebook/docusaurus/pull/3326) docs(v1): showcase user Casbin ([@hsluoyz](https://github.com/hsluoyz))
- [#3316](https://github.com/facebook/docusaurus/pull/3316) docs(v1): add Global CTO Forum to users ([@MirzayevFarid](https://github.com/MirzayevFarid))
- [#3310](https://github.com/facebook/docusaurus/pull/3310) docs(v2): add "T-Regx" website to showcase ([@Danon](https://github.com/Danon))
- [#3307](https://github.com/facebook/docusaurus/pull/3307) docs(v2): showcase SpotifyAPI-NET ([@JohnnyCrazy](https://github.com/JohnnyCrazy))
- [#3295](https://github.com/facebook/docusaurus/pull/3295) docs(v2): showcase Oxidizer ([@vandreleal](https://github.com/vandreleal))
- [#3287](https://github.com/facebook/docusaurus/pull/3287) docs: update README.md with some grammatical corrections ([@shalinikumari50](https://github.com/shalinikumari50))
- [#3271](https://github.com/facebook/docusaurus/pull/3271) docs(v2): fix typo ([@thehanimo](https://github.com/thehanimo))
- [#3277](https://github.com/facebook/docusaurus/pull/3277) docs(v1): Add Radity to users ([@tolunayakbulut](https://github.com/tolunayakbulut))
- [#3276](https://github.com/facebook/docusaurus/pull/3276) docs: corrected some few typos in the docusaurus tech docs ([@ajifrank75](https://github.com/ajifrank75))
- [#3249](https://github.com/facebook/docusaurus/pull/3249) docs(v2): fix migration command ([@BogdanDor](https://github.com/BogdanDor))
- [#3248](https://github.com/facebook/docusaurus/pull/3248) Added twitter badge and modified discord Badges ([@Souravdey777](https://github.com/Souravdey777))
- [#3251](https://github.com/facebook/docusaurus/pull/3251) docs(v2): fix migration command for earlier versions ([@teikjun](https://github.com/teikjun))
- [#3252](https://github.com/facebook/docusaurus/pull/3252) docs(v2): docs typos ([@olawanlejoel](https://github.com/olawanlejoel))
- [#3111](https://github.com/facebook/docusaurus/pull/3111) docs(v2): clarify theme-original and theme-init ([@Jonathannsegal](https://github.com/Jonathannsegal))
- [#3232](https://github.com/facebook/docusaurus/pull/3232) docs(v2): showcase user QA-Board ([@arthur-flam](https://github.com/arthur-flam))
- [#3205](https://github.com/facebook/docusaurus/pull/3205) docs: format reference links ([@lebogangolifant](https://github.com/lebogangolifant))
- [#3194](https://github.com/facebook/docusaurus/pull/3194) docs(v2): Added switch config docs to theme-classic API ([@Drewbi](https://github.com/Drewbi))
- [#3201](https://github.com/facebook/docusaurus/pull/3201) docs(v2): removed duplicate text under "Using React" section ([@boosh511](https://github.com/boosh511))
- [#3186](https://github.com/facebook/docusaurus/pull/3186) docs(v1): formatting changelog ([@slorber](https://github.com/slorber))
- `docusaurus`
- [#3202](https://github.com/facebook/docusaurus/pull/3202) fix(v2): fix svg loader ([@anshulrgoyal](https://github.com/anshulrgoyal))
#### :house: Internal
- `docusaurus-migrate`
- [#3323](https://github.com/facebook/docusaurus/pull/3323) test(v2): Add unit test for migration of config file ([@BogdanDor](https://github.com/BogdanDor))
- `docusaurus-theme-classic`
- [#3343](https://github.com/facebook/docusaurus/pull/3343) refactor(v2): announcement bar bad spelling + minor refactors ([@slorber](https://github.com/slorber))
- `docusaurus-plugin-content-blog`
- [#3339](https://github.com/facebook/docusaurus/pull/3339) test(v2): make blog posts unit test ordering determinate ([@BogdanDor](https://github.com/BogdanDor))
- `docusaurus-mdx-loader`, `docusaurus-plugin-content-blog`, `docusaurus-theme-classic`, `docusaurus-types`
- [#3306](https://github.com/facebook/docusaurus/pull/3306) chore(v2): Define type for markdown right table of contents ([@SamChou19815](https://github.com/SamChou19815))
- `docusaurus-module-type-aliases`, `docusaurus`
- [#3244](https://github.com/facebook/docusaurus/pull/3244) chore(v2): tighten up the TypeScript onboarding ([@orta](https://github.com/orta))
- `docusaurus-plugin-content-docs`, `docusaurus-theme-classic`, `docusaurus-utils`, `docusaurus`
- [#3245](https://github.com/facebook/docusaurus/pull/3245) refactor(v2): docs plugin refactor ([@slorber](https://github.com/slorber))
- `docusaurus`
- [#3282](https://github.com/facebook/docusaurus/pull/3282) chore(v2): fix javascript-serialize vulnerability ([@slorber](https://github.com/slorber))
- [#3265](https://github.com/facebook/docusaurus/pull/3265) chore(v2): upgrade terser-webpack-plugin ([@dschaller](https://github.com/dschaller))
- Other
- [#3241](https://github.com/facebook/docusaurus/pull/3241) chore(deps): bump prismjs from 1.20.0 to 1.21.0 ([@dependabot[bot]](https://github.com/apps/dependabot))
- [#3259](https://github.com/facebook/docusaurus/pull/3259) chore(v2): fix slow commits due to lint-staged ([@slorber](https://github.com/slorber))
- [#3197](https://github.com/facebook/docusaurus/pull/3197) chore(v2): lockfile update ([@slorber](https://github.com/slorber))
- `docusaurus-1.x`
- [#3218](https://github.com/facebook/docusaurus/pull/3218) chore(v1): release 1.14.6 ([@slorber](https://github.com/slorber))
#### :running_woman: Performance
- `docusaurus-plugin-client-redirects`, `docusaurus-theme-search-algolia`, `docusaurus`
- [#3238](https://github.com/facebook/docusaurus/pull/3238) refactor(v2): precompile ETA templates ([@slorber](https://github.com/slorber))
#### Committers: 39
- Ali Hosseini ([@Ako92](https://github.com/Ako92))
- Amy Lei ([@amy-lei](https://github.com/amy-lei))
- Anshul Goyal ([@anshulrgoyal](https://github.com/anshulrgoyal))
- Archit ([@arcvats](https://github.com/arcvats))
- Arthur Flam ([@arthur-flam](https://github.com/arthur-flam))
- Ben Gubler ([@nebrelbug](https://github.com/nebrelbug))
- Bogdan Doroschenko ([@BogdanDor](https://github.com/BogdanDor))
- Daniel Wilkowski ([@Danon](https://github.com/Danon))
- Derek ([@dschaller](https://github.com/dschaller))
- Drew Alexander ([@Drewbi](https://github.com/Drewbi))
- Fanny ([@fanny](https://github.com/fanny))
- Franklyn Chisom ([@ajifrank75](https://github.com/ajifrank75))
- François Chalifour ([@francoischalifour](https://github.com/francoischalifour))
- Govardhan Srinivas ([@govardhan-srinivas](https://github.com/govardhan-srinivas))
- Hani Mohammed ([@thehanimo](https://github.com/thehanimo))
- Jean-Marc Saad ([@JeanMarcSaad](https://github.com/JeanMarcSaad))
- Jonas Dellinger ([@JohnnyCrazy](https://github.com/JohnnyCrazy))
- Jonathan ([@Jonathannsegal](https://github.com/Jonathannsegal))
- Manuel Cepeda ([@mecm1993](https://github.com/mecm1993))
- Mirzayev Farid ([@MirzayevFarid](https://github.com/MirzayevFarid))
- Nisarag ([@FocalChord](https://github.com/FocalChord))
- Olawanle Joel ([@olawanlejoel](https://github.com/olawanlejoel))
- Orta Therox ([@orta](https://github.com/orta))
- Sam Zhou ([@SamChou19815](https://github.com/SamChou19815))
- Shubham Kumar ([@imskr](https://github.com/imskr))
- Sourav Dey ([@Souravdey777](https://github.com/Souravdey777))
- Sébastien Lorber ([@slorber](https://github.com/slorber))
- Teik Jun ([@teikjun](https://github.com/teikjun))
- Tolunay Akbulut ([@tolunayakbulut](https://github.com/tolunayakbulut))
- Vandré Leal ([@vandreleal](https://github.com/vandreleal))
- Vincent ([@Vinnl](https://github.com/Vinnl))
- Yang Luo ([@hsluoyz](https://github.com/hsluoyz))
- Yangshun Tay ([@yangshun](https://github.com/yangshun))
- [@adinaja](https://github.com/adinaja)
- [@leoigel](https://github.com/leoigel)
- [@shalinikumari50](https://github.com/shalinikumari50)
- alex busnelli ([@boosh511](https://github.com/boosh511))
- lebogang Olifant ([@lebogangolifant](https://github.com/lebogangolifant))
- ylemkimon ([@ylemkimon](https://github.com/ylemkimon))
## 2.0.0-alpha.61 (2020-08-01)
#### :rocket: New Feature

View file

@ -1,5 +1,5 @@
{
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"npmClient": "yarn",
"useWorkspaces": true,
"changelog": {

View file

@ -1,7 +1,7 @@
{
"name": "docusaurus",
"description": "Easy to Maintain Open Source Documentation Websites",
"version": "1.14.6",
"version": "2.0.0-alpha.62",
"license": "MIT",
"keywords": [
"documentation",

View file

@ -1,7 +1,7 @@
{
"name": "docusaurus-init",
"description": "Initialization script for Docusaurus",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"license": "MIT",
"preferGlobal": true,
"keywords": [

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/init",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Create Docusaurus app easily",
"repository": {
"type": "git",

View file

@ -1,6 +1,6 @@
{
"name": "docusaurus-2-bootstrap-template",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@ -11,8 +11,8 @@
"serve": "docusaurus serve"
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/preset-bootstrap": "^2.0.0-alpha.61",
"@docusaurus/core": "^2.0.0-alpha.62",
"@docusaurus/preset-bootstrap": "^2.0.0-alpha.62",
"@mdx-js/react": "^1.5.8",
"classnames": "^2.2.6",
"react": "^16.8.4",

View file

@ -1,6 +1,6 @@
{
"name": "docusaurus-2-classic-template",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@ -11,8 +11,8 @@
"serve": "docusaurus serve"
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/preset-classic": "^2.0.0-alpha.61",
"@docusaurus/core": "^2.0.0-alpha.62",
"@docusaurus/preset-classic": "^2.0.0-alpha.62",
"@mdx-js/react": "^1.5.8",
"clsx": "^1.1.1",
"react": "^16.8.4",

View file

@ -1,6 +1,6 @@
{
"name": "docusaurus-2-facebook-template",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@ -15,8 +15,8 @@
"prettier:diff": "prettier --config .prettierrc --list-different \"**/*.{js,md}\""
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/preset-classic": "^2.0.0-alpha.61",
"@docusaurus/core": "^2.0.0-alpha.62",
"@docusaurus/preset-classic": "^2.0.0-alpha.62",
"@mdx-js/react": "^1.5.8",
"clsx": "^1.1.1",
"react": "^16.8.4",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/mdx-loader",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Docusaurus Loader for MDX",
"main": "src/index.js",
"publishConfig": {
@ -13,8 +13,8 @@
"dependencies": {
"@babel/parser": "^7.9.4",
"@babel/traverse": "^7.9.0",
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/utils": "^2.0.0-alpha.61",
"@docusaurus/core": "^2.0.0-alpha.62",
"@docusaurus/utils": "^2.0.0-alpha.62",
"@mdx-js/mdx": "^1.5.8",
"@mdx-js/react": "^1.5.8",
"escape-html": "^1.0.3",
@ -30,7 +30,7 @@
"url-loader": "^4.1.0"
},
"devDependencies": {
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/types": "^2.0.0-alpha.62",
"remark": "^12.0.0",
"remark-mdx": "^1.5.8",
"to-vfile": "^6.0.0",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/migrate",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/migrate",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "A cli tool to migrate between different version of docusuarus",
"main": "lib/index.js",
"license": "MIT",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/module-type-aliases",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Docusaurus module type aliases",
"types": "./src/index.d.ts",
"publishConfig": {

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-client-redirects",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Client redirects plugin for Docusaurus",
"main": "lib/index.js",
"scripts": {
@ -12,9 +12,9 @@
},
"license": "MIT",
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/utils": "^2.0.0-alpha.61",
"@docusaurus/core": "^2.0.0-alpha.62",
"@docusaurus/types": "^2.0.0-alpha.62",
"@docusaurus/utils": "^2.0.0-alpha.62",
"@hapi/joi": "^17.1.1",
"@types/hapi__joi": "^17.1.2",
"chalk": "^3.0.0",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-content-blog",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Blog plugin for Docusaurus",
"main": "lib/index.js",
"types": "index.d.ts",
@ -16,14 +16,14 @@
"@types/hapi__joi": "^17.1.2"
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/mdx-loader": "^2.0.0-alpha.61",
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/utils": "^2.0.0-alpha.61",
"@docusaurus/utils-validation": "^2.0.0-alpha.61",
"@docusaurus/core": "^2.0.0-alpha.62",
"@docusaurus/mdx-loader": "^2.0.0-alpha.62",
"@docusaurus/types": "^2.0.0-alpha.62",
"@docusaurus/utils": "^2.0.0-alpha.62",
"@docusaurus/utils-validation": "^2.0.0-alpha.62",
"@hapi/joi": "^17.1.1",
"feed": "^4.1.0",
"chalk": "^3.0.0",
"feed": "^4.1.0",
"fs-extra": "^8.1.0",
"globby": "^10.0.1",
"loader-utils": "^1.2.3",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-content-docs",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Docs content plugin for Docusaurus",
"main": "lib/index.js",
"types": "src/plugin-content-docs.d.ts",
@ -13,18 +13,18 @@
},
"license": "MIT",
"devDependencies": {
"@docusaurus/module-type-aliases": "^2.0.0-alpha.61",
"@docusaurus/module-type-aliases": "^2.0.0-alpha.62",
"@types/hapi__joi": "^17.1.2",
"@types/picomatch": "^2.2.1",
"commander": "^5.0.0",
"picomatch": "^2.1.1"
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/mdx-loader": "^2.0.0-alpha.61",
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/utils": "^2.0.0-alpha.61",
"@docusaurus/utils-validation": "^2.0.0-alpha.61",
"@docusaurus/core": "^2.0.0-alpha.62",
"@docusaurus/mdx-loader": "^2.0.0-alpha.62",
"@docusaurus/types": "^2.0.0-alpha.62",
"@docusaurus/utils": "^2.0.0-alpha.62",
"@docusaurus/utils-validation": "^2.0.0-alpha.62",
"@hapi/joi": "17.1.1",
"chalk": "^3.0.0",
"execa": "^3.4.0",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-content-pages",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Pages content plugin for Docusaurus",
"main": "lib/index.js",
"types": "src/plugin-content-pages.d.ts",
@ -16,11 +16,11 @@
"@types/hapi__joi": "^17.1.2"
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/mdx-loader": "^2.0.0-alpha.61",
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/utils": "^2.0.0-alpha.61",
"@docusaurus/utils-validation": "^2.0.0-alpha.61",
"@docusaurus/core": "^2.0.0-alpha.62",
"@docusaurus/mdx-loader": "^2.0.0-alpha.62",
"@docusaurus/types": "^2.0.0-alpha.62",
"@docusaurus/utils": "^2.0.0-alpha.62",
"@docusaurus/utils-validation": "^2.0.0-alpha.62",
"@hapi/joi": "17.1.1",
"globby": "^10.0.1",
"loader-utils": "^1.2.3",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-debug",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Debug plugin for Docusaurus",
"main": "lib/index.js",
"scripts": {
@ -12,8 +12,8 @@
},
"license": "MIT",
"dependencies": {
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/utils": "^2.0.0-alpha.61",
"@docusaurus/types": "^2.0.0-alpha.62",
"@docusaurus/utils": "^2.0.0-alpha.62",
"react-json-view": "^1.19.1"
},
"peerDependencies": {

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-google-analytics",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Global analytics (analytics.js) plugin for Docusaurus",
"main": "src/index.js",
"publishConfig": {

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-google-gtag",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Global Site Tag (gtag.js) plugin for Docusaurus",
"main": "src/index.js",
"publishConfig": {

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-ideal-image",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Docusaurus Plugin to generate an almost ideal image (responsive, lazy-loading, and low quality placeholder)",
"main": "lib/index.js",
"scripts": {
@ -15,8 +15,8 @@
"fs-extra": "^9.0.0"
},
"dependencies": {
"@docusaurus/lqip-loader": "^2.0.0-alpha.61",
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/lqip-loader": "^2.0.0-alpha.62",
"@docusaurus/types": "^2.0.0-alpha.62",
"@endiliey/react-ideal-image": "^0.0.11",
"@endiliey/responsive-loader": "^1.3.2",
"react-waypoint": "^9.0.2",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-pwa",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Docusaurus Plugin to add PWA support",
"main": "src/index.js",
"publishConfig": {

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/plugin-sitemap",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Simple sitemap generation plugin for Docusaurus",
"main": "lib/index.js",
"scripts": {
@ -15,7 +15,7 @@
"@types/hapi__joi": "^17.1.2"
},
"dependencies": {
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/types": "^2.0.0-alpha.62",
"@hapi/joi": "17.1.1",
"fs-extra": "^8.1.0",
"sitemap": "^3.2.2"

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/preset-bootstrap",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Preset for bootstrap Docusaurus",
"main": "src/index.js",
"license": "MIT",
@ -8,10 +8,10 @@
"access": "public"
},
"dependencies": {
"@docusaurus/plugin-content-blog": "^2.0.0-alpha.61",
"@docusaurus/plugin-content-docs": "^2.0.0-alpha.61",
"@docusaurus/plugin-content-pages": "^2.0.0-alpha.61",
"@docusaurus/theme-bootstrap": "^2.0.0-alpha.61"
"@docusaurus/plugin-content-blog": "^2.0.0-alpha.62",
"@docusaurus/plugin-content-docs": "^2.0.0-alpha.62",
"@docusaurus/plugin-content-pages": "^2.0.0-alpha.62",
"@docusaurus/theme-bootstrap": "^2.0.0-alpha.62"
},
"peerDependencies": {
"@docusaurus/core": "^2.0.0",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/preset-classic",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Preset for classic Docusaurus",
"main": "src/index.js",
"publishConfig": {
@ -8,15 +8,15 @@
},
"license": "MIT",
"dependencies": {
"@docusaurus/plugin-content-blog": "^2.0.0-alpha.61",
"@docusaurus/plugin-content-docs": "^2.0.0-alpha.61",
"@docusaurus/plugin-content-pages": "^2.0.0-alpha.61",
"@docusaurus/plugin-debug": "^2.0.0-alpha.61",
"@docusaurus/plugin-google-analytics": "^2.0.0-alpha.61",
"@docusaurus/plugin-google-gtag": "^2.0.0-alpha.61",
"@docusaurus/plugin-sitemap": "^2.0.0-alpha.61",
"@docusaurus/theme-classic": "^2.0.0-alpha.61",
"@docusaurus/theme-search-algolia": "^2.0.0-alpha.61"
"@docusaurus/plugin-content-blog": "^2.0.0-alpha.62",
"@docusaurus/plugin-content-docs": "^2.0.0-alpha.62",
"@docusaurus/plugin-content-pages": "^2.0.0-alpha.62",
"@docusaurus/plugin-debug": "^2.0.0-alpha.62",
"@docusaurus/plugin-google-analytics": "^2.0.0-alpha.62",
"@docusaurus/plugin-google-gtag": "^2.0.0-alpha.62",
"@docusaurus/plugin-sitemap": "^2.0.0-alpha.62",
"@docusaurus/theme-classic": "^2.0.0-alpha.62",
"@docusaurus/theme-search-algolia": "^2.0.0-alpha.62"
},
"peerDependencies": {
"@docusaurus/core": "^2.0.0",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/theme-bootstrap",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Bootstrap theme for docusaurus",
"main": "src/index.js",
"license": "MIT",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/theme-classic",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Classic theme for Docusaurus",
"main": "src/index.js",
"types": "src/types.d.ts",
@ -15,6 +15,8 @@
"prettier": "prettier --config ../../.prettierrc --write \"**/*.{js,ts}\""
},
"dependencies": {
"@docusaurus/types": "^2.0.0-alpha.62",
"@docusaurus/utils-validation": "^2.0.0-alpha.62",
"@hapi/joi": "^17.1.1",
"@mdx-js/mdx": "^1.5.8",
"@mdx-js/react": "^1.5.8",
@ -29,12 +31,10 @@
"prop-types": "^15.7.2",
"react-router-dom": "^5.1.2",
"react-toggle": "^4.1.1",
"use-onclickoutside": "^0.3.1",
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/utils-validation": "^2.0.0-alpha.61"
"use-onclickoutside": "^0.3.1"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "^2.0.0-alpha.61",
"@docusaurus/module-type-aliases": "^2.0.0-alpha.62",
"@types/hapi__joi": "^17.1.2"
},
"peerDependencies": {

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/theme-live-codeblock",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Docusaurus Live CodeBlock",
"main": "src/index.js",
"publishConfig": {

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/theme-search-algolia",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Algolia search component for Docusaurus",
"main": "src/index.js",
"publishConfig": {
@ -9,7 +9,7 @@
"license": "MIT",
"dependencies": {
"@docsearch/react": "^1.0.0-alpha.27",
"@docusaurus/utils": "^2.0.0-alpha.61",
"@docusaurus/utils": "^2.0.0-alpha.62",
"@hapi/joi": "^17.1.1",
"algoliasearch": "^4.0.0",
"algoliasearch-helper": "^3.1.1",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/types",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Common used typings for Docusaurus packages",
"main": "./src/index.js",
"types": "./src/index.d.ts",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/utils-validation",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Node validation utility functions for Docusaurus packages",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/utils",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Node utility functions for Docusaurus packages",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",

View file

@ -1,7 +1,7 @@
{
"name": "@docusaurus/core",
"description": "Easy to Maintain Open Source Documentation Websites",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"license": "MIT",
"publishConfig": {
"access": "public"
@ -30,7 +30,7 @@
"url": "https://github.com/facebook/docusaurus/issues"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "^2.0.0-alpha.61",
"@docusaurus/module-type-aliases": "^2.0.0-alpha.62",
"@types/detect-port": "^1.3.0",
"@types/hapi__joi": "^17.1.2"
},
@ -45,9 +45,9 @@
"@babel/preset-typescript": "^7.9.0",
"@babel/runtime": "^7.9.2",
"@babel/runtime-corejs3": "^7.10.4",
"@docusaurus/types": "^2.0.0-alpha.61",
"@docusaurus/utils": "^2.0.0-alpha.61",
"@docusaurus/utils-validation": "^2.0.0-alpha.61",
"@docusaurus/types": "^2.0.0-alpha.62",
"@docusaurus/utils": "^2.0.0-alpha.62",
"@docusaurus/utils-validation": "^2.0.0-alpha.62",
"@endiliey/static-site-generator-webpack-plugin": "^4.0.0",
"@hapi/joi": "^17.1.1",
"@svgr/webpack": "^5.4.0",

View file

@ -1,6 +1,6 @@
{
"name": "@docusaurus/lqip-loader",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "Low Quality Image Placeholders (LQIP) loader for webpack",
"main": "src/index.js",
"publishConfig": {

View file

@ -1,6 +1,6 @@
{
"name": "stylelint-copyright",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"description": "stylelint plugin to check css files for a copyright header",
"main": "index.js",
"license": "MIT",

View file

@ -1,6 +1,6 @@
{
"name": "docusaurus-1-website",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"private": true,
"scripts": {
"start": "docusaurus-start",
@ -14,6 +14,6 @@
"crowdin-download": "crowdin --config ../crowdin.yaml download -b master"
},
"dependencies": {
"docusaurus": "^1.14.5"
"docusaurus": "^2.0.0-alpha.62"
}
}

View file

@ -1,6 +1,6 @@
{
"name": "docusaurus-2-website",
"version": "2.0.0-alpha.61",
"version": "2.0.0-alpha.62",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@ -20,12 +20,12 @@
"netlify:test": "yarn netlify:build:deployPreview && yarn netlify dev --debug"
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/plugin-client-redirects": "^2.0.0-alpha.61",
"@docusaurus/plugin-ideal-image": "^2.0.0-alpha.61",
"@docusaurus/plugin-pwa": "^2.0.0-alpha.61",
"@docusaurus/preset-classic": "^2.0.0-alpha.61",
"@docusaurus/theme-live-codeblock": "^2.0.0-alpha.61",
"@docusaurus/core": "^2.0.0-alpha.62",
"@docusaurus/plugin-client-redirects": "^2.0.0-alpha.62",
"@docusaurus/plugin-ideal-image": "^2.0.0-alpha.62",
"@docusaurus/plugin-pwa": "^2.0.0-alpha.62",
"@docusaurus/preset-classic": "^2.0.0-alpha.62",
"@docusaurus/theme-live-codeblock": "^2.0.0-alpha.62",
"clsx": "^1.1.1",
"color": "^3.1.2",
"npm-to-yarn": "^1.0.0-2",

View file

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

View file

@ -0,0 +1,220 @@
---
id: blog
title: Blog
---
## Initial setup
To setup your site's blog, start by creating a `blog` directory.
Then, add an item link to your blog within `docusaurus.config.js`:
```js title="docusaurus.config.js"
module.exports = {
themeConfig: {
// ...
navbar: {
items: [
// ...
// highlight-next-line
{to: 'blog', label: 'Blog', position: 'left'}, // or position: 'right'
],
},
},
};
```
## Adding posts
To publish in the blog, create a file within the blog directory with a formatted name of `YYYY-MM-DD-my-blog-post-title.md`. The post date is extracted from the file name.
For example, at `my-website/blog/2019-09-05-hello-docusaurus-v2.md`:
```yml
---
title: Welcome Docusaurus v2
author: Joel Marcey
author_title: Co-creator of Docusaurus 1
author_url: https://github.com/JoelMarcey
author_image_url: https://graph.facebook.com/611217057/picture/?height=200&width=200
tags: [hello, docusaurus-v2]
description: This is my first post on Docusaurus 2.
image: https://i.imgur.com/mErPwqL.png
hide_table_of_contents: false
---
Welcome to this blog. This blog is created with [**Docusaurus 2 alpha**](https://v2.docusaurus.io/).
<!--truncate-->
This is my first post on Docusaurus 2.
A whole bunch of exploration to follow.
```
## Header options
The only required field is `title`; however, we provide options to add author information to your blog post as well along with other options.
- `author` - The author name to be displayed.
- `author_url` - The URL that the author's name will be linked to. This could be a GitHub, Twitter, Facebook profile URL, etc.
- `author_image_url` - The URL to the author's thumbnail image.
- `author_title` - A description of the author.
- `title` - The blog post title.
- `tags` - A list of strings to tag to your post.
- `draft` - A boolean flag to indicate that the blog post is work-in-progress and therefore should not be published yet. However, draft blog posts will be displayed during development.
- `description`: The description of your post, 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.
- `hide_table_of_contents`: Whether to hide the table of contents to the right. By default it is `false`.
## 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 these will be part of the blog post summary.
Even this.
<!--truncate-->
But anything from here on down will not be.
Not this.
Or this.
```
## Feed
You can generate RSS/ Atom feed by passing feedOptions.
```ts
feedOptions?: {
type: 'rss' | 'atom' | 'all';
title?: string;
description?: string;
copyright: string;
language?: string; // possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
};
```
Example usage:
```js {8-11} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
feedOptions: {
type: 'all',
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`,
},
},
},
],
],
};
```
Accessing the feed:
The feed for RSS can be found at:
```text
https://{your-domain}/blog/rss.xml
```
and for Atom:
```text
https://{your-domain}/blog/atom.xml
```
## Advanced topics
### Blog-only mode
You can run your Docusaurus 2 site without a landing page and instead have your blog's post list page as the index page. Set the `routeBasePath` to be `'/'` to indicate it's the root path.
```js {9} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
path: './blog',
routeBasePath: '/', // Set this value to '/'.
},
},
],
],
};
```
:::caution
Don't forget to delete the existing homepage at `./src/pages/index.js` or else there will be two files mapping to the same route!
:::
You can also add meta description to the blog list page for better SEO:
```js {8} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
blogDescription: 'A docusaurus powered blog!',
},
},
],
],
};
```
### Multiple blogs
By default, the classic theme assumes only one blog per website and hence includes only one instance of the blog plugin. If you would like to have multiple blogs on a single website, it's possible too! You can add another blog by specifying another blog plugin in the `plugins` option for `docusaurus.config.js`.
Set the `routeBasePath` to the URL route that you want your second blog to be accessed on. Note that the `routeBasePath` here has to be different from the first blog or else there could be a collision of paths! Also, set `path` to the path to the directory containing your second blog's entries.
As documented for [multi-instance plugins](./using-plugins.md#multi-instance-plugins-and-plugin-ids), you need to assign a unique id to the plugins.
```js title="docusaurus.config.js"
module.exports = {
// ...
plugins: [
[
'@docusaurus/plugin-content-blog',
{
/**
* Required for any multi-instance plugin
*/
id: 'second-blog',
/**
* URL route for the blog section of your site.
* *DO NOT* include a trailing slash.
*/
routeBasePath: 'my-second-blog',
/**
* Path to data on filesystem relative to site dir.
*/
path: './my-second-blog',
},
],
],
};
```
As an example, we host a second blog [here](/second-blog).

View file

@ -0,0 +1,128 @@
---
id: cli
title: CLI
---
Docusaurus provides a set of scripts to help you generate, serve, and deploy your website.
Once your website is bootstrapped, the website source will contain the Docusaurus scripts that you can invoke with your package manager:
```json title="package.json"
{
// ...
"scripts": {
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy"
}
}
```
## Docusaurus CLI commands
Below is a list of Docusaurus CLI commands and their usages:
<!-- TODO: init docs after the init command is implemented
### `docusaurus init`
The `docusaurus init` command is intended to be used with `docusaurus` installed globally:
```shell
$ yarn global add docusaurus
# or
$ npm install --global docusaurus
```
-->
### `docusaurus start`
Builds and serves a preview of your site locally with [Webpack Dev Server](https://webpack.js.org/configuration/dev-server).
#### Options
| Name | Default | Description |
| --- | --- | --- |
| `--port` | `3000` | Specifies the port of the dev server. |
| `--host` | `localhost` | Specify a host to use. For example, if you want your server to be accessible externally, you can use `--host 0.0.0.0`. |
| `--hot-only` | `false` | Enables Hot Module Replacement without page refresh as fallback in case of build failures. More information [here](https://webpack.js.org/configuration/dev-server/#devserverhotonly). |
| `--no-open` | `false` | Do not open automatically the page in the browser. |
| `--poll` | `false` | Use polling of files rather than watching for live reload as a fallback in environments where watching doesn't work. More information [here](https://webpack.js.org/configuration/watch/#watchoptionspoll). |
:::important
Please note that some functionality (for example, anchor links) will not work in development. The functionality will work as expected in production.
:::
### `docusaurus build`
Compiles your site for production.
#### Options
| Name | Default | Description |
| --- | --- | --- |
| `--bundle-analyzer` | `false` | Analyze your bundle with the [webpack bundle analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer). |
| `--out-dir` | `build` | The full path for the new output directory, relative to the current workspace. |
| `--no-minify` | `false` | Build website without minimizing JS/CSS bundles. |
### `docusaurus swizzle`
:::caution
We highly discourage swizzling of components until we've reached a Beta stage. The components APIs have been changing rapidly and are likely to keep changing until we reach Beta. Stick with the default appearance for now if possible to save yourself some potential pain in future.
:::
Change any Docusaurus theme components to your liking with `docusaurus swizzle`.
```shell
docusaurus swizzle [themeName] [componentName] [siteDir]
# Example (leaving out the siteDir to indicate this directory)
docusaurus swizzle @docusaurus/theme-classic DocSidebar
```
Running the command will copy the relevant theme files to your site folder. You may then make any changes to it and Docusaurus will use it instead of the one provided from the theme.
`docusaurus swizzle` without `themeName` lists all the themes available for swizzling similarly `docusaurus swizzle <themeName>` without `componentName` lists all the components available for swizzling.
#### Options
| Name | Description |
| ------------------ | -------------------------------------- |
| `themeName` | The name of the theme you are using. |
| `swizzleComponent` | The name of the component to swizzle. |
| `--danger` | Allow swizzling of unstable components |
| `--typescript` | Swizzle typescript components |
To unswizzle a component, simply delete the files of the swizzled component.
<!--
TODO a separate section for swizzle tutorial.
To learn more about swizzling, check [here](#).
-->
### `docusaurus deploy`
Deploys your site with [GitHub Pages](https://pages.github.com/). Check out the docs on [deployment](deployment.md/#deploying-to-github-pages) for more details.
#### Options
| Name | Default | Description |
| --- | --- | --- |
| `--out-dir` | `build` | The full path for the new output directory, relative to the current workspace. |
| `--skip-build` | `false` | Deploy website without building it. This may be useful when using custom deploy script. |
### `docusaurus serve`
Serve your built website localy.
| Name | Default | Description |
| --- | --- | --- |
| `--port` | `3000` | Use specified port |
| `--dir` | `build` | The full path for the output directory, relative to the current workspace |
| `--build` | `false` | Build website before serving |
| `--host` | `localhost` | Specify a host to use. For example, if you want your server to be accessible externally, you can use `--host 0.0.0.0`. |

View file

@ -0,0 +1,164 @@
---
id: configuration
title: Configuration
---
Docusaurus has a unique take on configurations. We encourage you to congregate information of your site into one place. We guard the fields of this file, and facilitate making this data object accessible across your site.
Keeping a well-maintained `docusaurus.config.js` helps you, your collaborators, and your open source contributors be able to focus on documentation while still being able to customize the site.
## What goes into a `docusaurus.config.js`?
You should not have to write your `docusaurus.config.js` from scratch even if you are developing your site. All templates come with a `docusaurus.config.js` that includes defaults for the common options.
However, it can be helpful if you have a high-level understanding of how the configurations are designed and implemented.
The high-level overview of Docusaurus configuration can be categorized into:
- [What goes into a `docusaurus.config.js`?](#what-goes-into-a-docusaurusconfigjs)
- [Site metadata](#site-metadata)
- [Deployment configurations](#deployment-configurations)
- [Theme, plugin, and preset configurations](#theme-plugin-and-preset-configurations)
- [Custom configurations](#custom-configurations)
- [Customizing Babel Configuration](#customizing-babel-configuration)
For exact reference to each of the configurable fields, you may refer to [**`docusaurus.config.js` API reference**](api/docusaurus.config.js.md).
### Site metadata
Site metadata contains the essential global metadata such as `title`, `url`, `baseUrl` and `favicon`.
They are used in a number of places such as your site's title and headings, browser tab icon, social sharing (Facebook, Twitter) information or even to generate the correct path to serve your static files.
### Deployment configurations
Deployment configurations such as `projectName` and `organizationName` are used when you deploy your site with the `deploy` command.
It is recommended to check the [deployment docs](deployment.md) for more information.
### Theme, plugin, and preset configurations
List the [theme](using-themes.md), [plugins](using-plugins.md), and [presets](presets.md) for your site in the `themes`, `plugins`, and `presets` fields, respectively. These are typically npm packages:
```js title="docusaurus.config.js"
module.exports = {
// ...
plugins: [
'@docusaurus/plugin-content-blog',
'@docusaurus/plugin-content-pages',
],
themes: ['@docusaurus/theme-classic'],
};
```
They can also be loaded from local directories:
```js title="docusaurus.config.js"
const path = require('path');
module.exports = {
// ...
themes: [path.resolve(__dirname, '/path/to/docusaurus-local-theme')],
};
```
To specify options for a plugin or theme, replace the name of the plugin or theme in the config file with an array containing the name and an options object:
```js title="docusaurus.config.js"
module.exports = {
// ...
plugins: [
[
'@docusaurus/plugin-content-blog',
{
path: 'blog',
routeBasePath: 'blog',
include: ['*.md', '*.mdx'],
// ...
},
],
'@docusaurus/plugin-content-pages',
],
};
```
To specify options for a plugin or theme that is bundled in a preset, pass the options through the `presets` field. In this example, `docs` refers to `@docusaurus/plugin-content-docs` and `theme` refers to `@docusaurus/theme-classic`.
```js title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.js'),
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
};
```
For further help configuring themes, plugins, and presets, see [Using Themes](using-themes.md), [Using Plugins](using-plugins.md), and [Using Presets](presets.md).
### Custom configurations
Docusaurus guards `docusaurus.config.js` from unknown fields. To add custom fields, define them in `customFields`.
Example:
```js title="docusaurus.config.js"
module.exports = {
// ...
// highlight-start
customFields: {
image: '',
keywords: [],
},
// highlight-end
// ...
};
```
## Accessing configuration from components
Your configuration object will be made available to all the components of your site. And you may access them via React context as `siteConfig`.
Basic example:
```jsx
import React from 'react';
// highlight-next-line
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
const Hello = () => {
// highlight-start
const {siteConfig} = useDocusaurusContext();
// highlight-end
const {title, tagline} = siteConfig;
return <div>{`${title} · ${tagline}`}</div>;
};
```
:::tip
If you just want to use those fields on the client side, you could create your own JS files and import them as ES6 modules, there is no need to put them in `docusaurus.config.js`.
:::
## Customizing Babel Configuration
For new Docusaurus projects, we automatically generated a `babel.config.js` in project root.
```js title="babel.config.js"
module.exports = {
presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
};
```
Most of the times, this configuration will work just fine. If you want to customize it, you can directly edit this file to customize babel configuration. For your changes to take effect, you need to restart Docusaurus devserver.

View file

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

View file

@ -0,0 +1,371 @@
---
id: deployment
title: Deployment
---
To build the static files of your website for production, run:
```bash npm2yarn
npm run build
```
Once it finishes, the static files will be generated within the `build/` directory.
You can deploy your site to static site hosting services such as [Vercel](https://vercel.com/), [GitHub Pages](https://pages.github.com/), [Netlify](https://www.netlify.com/), [Render](https://render.com/static-sites), and [Surge](https://surge.sh/help/getting-started-with-surge). Docusaurus sites are statically rendered so they work without JavaScript too!
## Testing Build Local
It is important to test build before deploying to a production. Docusaurus includes a [`docusaurus serve`](cli.md#docusaurus-serve) command to test build localy.
```bash npm2yarn
npm run serve
```
## Self Hosting
:::warning
It is not the most performant solution
:::
Docusaurus can be self hosted using [`docusaurus serve`](cli.md#docusaurus-serve). Change port using `--port` and `--host` to change host.
```bash npm2yarn
npm run serve --build --port 80 --host 0.0.0.0
```
## Deploying to GitHub Pages
Docusaurus provides an easy way to publish to [GitHub Pages](https://pages.github.com/). Which is hosting that comes for free with every GitHub repository.
### `docusaurus.config.js` settings
First, modify your `docusaurus.config.js` and add the required params:
| Name | Description |
| --- | --- |
| `organizationName` | The GitHub user or organization that owns the repository. If you are the owner, it is your GitHub username. In the case of Docusaurus, it is "_facebook_" which is the GitHub organization that owns Docusaurus. |
| `projectName` | The name of the GitHub repository. For example, the repository name for Docusaurus is "docusaurus", so the project name is "docusaurus". |
| `url` | URL for your GitHub Page's user/organization page. This is commonly https://_username_.github.io. |
| `baseUrl` | Base URL for your project. For projects hosted on GitHub pages, it follows the format "/_projectName_/". For https://github.com/facebook/docusaurus, `baseUrl` is `/docusaurus/`. |
In case you want to use your custom domain for GitHub Pages, create a `CNAME` file in the `static` directory. Anything within the `static` directory will be copied to the root of the `build` directory for deployment.
You may refer to GitHub Pages' documentation [User, Organization, and Project Pages](https://help.github.com/en/articles/user-organization-and-project-pages) for more details.
Example:
```jsx {3-6} title="docusaurus.config.js"
module.exports = {
// ...
url: 'https://endiliey.github.io', // Your website URL
baseUrl: '/',
projectName: 'endiliey.github.io',
organizationName: 'endiliey',
// ...
};
```
:::warning
By default, GitHub Pages runs published files through [Jekyll](https://jekyllrb.com/). Since Jekyll will discard any files that begin with `_`, it is recommended that you disable Jekyll by adding an empty file named `.nojekyll` file to your `static` directory.
:::
### Environment settings
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`. |
Optional parameters, also set as environment variables:
| Name | Description |
| --- | --- |
| `USE_SSH` | Set to `true` to use SSH instead of the default HTTPS for the connection to the GitHub repo. |
| `DEPLOYMENT_BRANCH` | The branch that the website will be deployed to, defaults to `gh-pages` for normal repos and `master` for repository names ending in `github.io`. |
| `CURRENT_BRANCH` | The branch that contains the latest docs changes that will be deployed. Usually, the branch will be `master`, but it could be any branch (default or otherwise) except for `gh-pages`. If nothing is set for this variable, then the current branch will be used. |
### Deploy
Finally, to deploy your site to GitHub Pages, run:
**Bash**
```bash
GIT_USER=<GITHUB_USERNAME> yarn deploy
```
**Windows**
```batch
cmd /C "set "GIT_USER=<GITHUB_USERNAME>" && yarn deploy"
```
### Triggering deployment with GitHub Actions
[GitHub Actions](https://help.github.com/en/actions) allow you to automate, customize, and execute your software development workflows right in your repository.
This workflow assumes your documentation resided in `documentation` branch of your repository and your [publishing source](https://help.github.com/en/github/working-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site) is configured for `gh-pages` branch.
1. Generate a new [SSH key](https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent).
1. By default, your public key should have been created in `~/.ssh/id_rsa.pub` or use the name you've provided in the previous step to add your key to [GitHub deploy keys](https://developer.github.com/v3/guides/managing-deploy-keys/).
1. Copy key to clipboard with `xclip -sel clip < ~/.ssh/id_rsa.pub` and paste it as a [deploy key](https://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys) in your repository. Copy file content if the command line doesn't work for you. Check the box for `Allow write access` before saving your deployment key.
1. You'll need your private key as a [GitHub secret](https://help.github.com/en/actions/configuring-and-managing-workflows/creating-and-storing-encrypted-secrets) to allow Docusaurus to run the deployment for you.
1. Copy your private key with `xclip -sel clip < ~/.ssh/id_rsa` and paste a GitHub secret with name `GH_PAGES_DEPLOY`. Copy file content if the command line doesn't work for you. Save your secret.
1. Create you [documentation workflow file](https://help.github.com/en/actions/configuring-and-managing-workflows/configuring-a-workflow#creating-a-workflow-file) in `.github/workflows/`. In this example it's `documentation.yml`.
```yaml title="documentation.yml"
name: documentation
on:
pull_request:
branches: [documentation]
push:
branches: [documentation]
jobs:
checks:
if: github.event_name != 'push'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: '12.x'
- name: Test Build
run: |
if [ -e yarn.lock ]; then
yarn install --frozen-lockfile
elif [ -e package-lock.json ]; then
npm ci
else
npm i
fi
npm run build
gh-release:
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: '12.x'
- name: Add key to allow access to repository
env:
SSH_AUTH_SOCK: /tmp/ssh_agent.sock
run: |
mkdir -p ~/.ssh
ssh-keyscan github.com >> ~/.ssh/known_hosts
echo "${{ secrets.GH_PAGES_DEPLOY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
cat <<EOT >> ~/.ssh/config
Host github.com
HostName github.com
IdentityFile ~/.ssh/id_rsa
EOT
- name: Release to GitHub Pages
env:
USE_SSH: true
GIT_USER: git
run: |
git config --global user.email "actions@gihub.com"
git config --global user.name "gh-actions"
if [ -e yarn.lock ]; then
yarn install --frozen-lockfile
elif [ -e package-lock.json ]; then
npm ci
else
npm i
fi
npx docusaurus deploy
```
1. Now when a new pull request arrives towards your repository in branch `documentation` it will automatically ensure that Docusaurus build is successful.
1. When pull request is merged to `documentation` branch or someone pushes to `documentation` branch directly it will be built and deployed to `gh-pages` branch.
1. After this step, your updated documentation will be available on the GitHub pages.
### Triggering deployment with Travis CI
Continuous integration (CI) services are typically used to perform routine tasks whenever new commits are checked in to source control. These tasks can be any combination of running unit tests and integration tests, automating builds, publishing packages to NPM, and deploying changes to your website. All you need to do to automate the deployment of your website is to invoke the `yarn deploy` script whenever your website is updated. The following section covers how to do just that using [Travis CI](https://travis-ci.com/), a popular continuous integration service provider.
1. Go to https://github.com/settings/tokens and generate a new [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/).
1. Using your GitHub account, [add the Travis CI app](https://github.com/marketplace/travis-ci) to the repository you want to activate.
1. Open your Travis CI dashboard. The URL looks like https://travis-ci.com/USERNAME/REPO, and navigate to the `More options` > `Setting` > `Environment Variables` section of your repository.
1. Create a new environment variable named `GH_TOKEN` with your newly generated token as its value, then `GH_EMAIL` (your email address) and `GH_NAME` (your GitHub username).
1. Create a `.travis.yml` on the root of your repository with the following:
```yaml title=".travis.yml"
language: node_js
node_js:
- '10'
branches:
only:
- master
cache:
yarn: true
script:
- git config --global user.name "${GH_NAME}"
- git config --global user.email "${GH_EMAIL}"
- echo "machine github.com login ${GH_NAME} password ${GH_TOKEN}" > ~/.netrc
- yarn && GIT_USER="${GH_NAME}" yarn deploy
```
Now, whenever a new commit lands in `master`, Travis CI will run your suite of tests and if everything passes, your website will be deployed via the `yarn deploy` script.
### Using Azure Pipelines
1. Sign Up at [Azure Pipelines](https://azure.microsoft.com/en-us/services/devops/pipelines/) if you haven't already.
1. Create an organization and within the organization create a project and connect your repository from GitHub.
1. Go to https://github.com/settings/tokens and generate a new [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/) with repository scope.
1. In the project page (which looks like https://dev.azure.com/ORG_NAME/REPO_NAME/_build) create a new pipeline with the following text. Also, click on edit and add a new environment variable named `GH_TOKEN` with your newly generated token as its value, then `GH_EMAIL` (your email address) and `GH_NAME` (your GitHub username). Make sure to mark them as secret. Alternatively, you can also add a file named `azure-pipelines.yml` at yout repository root.
```yaml title="azure-pipelines.yml"
trigger:
- master
pool:
vmImage: 'ubuntu-latest'
steps:
- checkout: self
persistCredentials: true
- task: NodeTool@0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- script: |
git config --global user.name "${GH_NAME}"
git config --global user.email "${GH_EMAIL}"
git checkout -b master
echo "machine github.com login ${GH_NAME} password ${GH_TOKEN}" > ~/.netrc
yarn && GIT_USER="${GH_NAME}" yarn deploy
env:
GH_NAME: $(GH_NAME)
GH_EMAIL: $(GH_EMAIL)
GH_TOKEN: $(GH_TOKEN)
displayName: 'yarn install and build'
```
## Deploying to Netlify
To deploy your Docusaurus 2 sites to [Netlify](https://www.netlify.com/), first make sure the following options are properly configured:
```js {2-3} title="docusaurus.config.js"
module.exports = {
url: 'https://docusaurus-2.netlify.com', // Url to your site with no trailing slash
baseUrl: '/', // Base directory of your site relative to your repo
// ...
};
```
Then, [create your site with Netlify](https://app.netlify.com/start).
While you set up the site, specify the build commands and directories as follows:
- build command: `npm run build`
- build directory: `build`
If you did not configure these build options, you may still go to "Site settings" -> "Build and deploy" after your site is created.
Once properly configured with the above options, your site should deploy and automatically redeploy upon merging to your deploy branch, which defaults to `master`.
:::important
Make sure to disable Netlify setting `Pretty URLs` to prevent lowercased URLs, unnecessary redirects and 404 errors.
:::
## Deploying to Vercel
Deploying your Docusaurus project to [Vercel](https://vercel.com/) will provide you with [various benefits](https://vercel.com/) in the areas of performance and ease of use.
Most importantly, however, deploying a Docusaurus project only takes a couple of seconds:
1. First, install their [command-line interface](https://vercel.com/download):
```bash
npm i -g vercel
```
1. Run a single command inside the root directory of your project:
```bash
vercel
```
**That's all.** Your docs will automatically be deployed.
Now you can connect your site to [GitHub](https://zeit.co/github) or [GitLab](https://zeit.co/gitlab) to automatically receive a new deployment every time you push a commit.
## Deploying to Render
Render offers [free static site hosting](https://render.com/docs/static-sites) with fully managed SSL, custom domains, a global CDN and continuous auto-deploy from your Git repo. Deploy your app in just a few minutes by following these steps.
1. Create a new **Web Service** on Render, and give Render permission to access your Docusaurus repo.
1. Select the branch to deploy. The default is `master`.
1. Enter the following values during creation.
| Field | Value |
| --------------------- | ------------- |
| **Environment** | `Static Site` |
| **Build Command** | `yarn build` |
| **Publish Directory** | `build` |
That's it! Your app will be live on your Render URL as soon as the build finishes.
## Deploying to Surge
Surge is a [static web hosting platform](https://surge.sh/help/getting-started-with-surge), it is used to deploy your Docusaurus project from the command line in a minute. Deploying your project to Surge is easy and it is also free (including a custom domain and SSL).
Deploy your app in a matter of seconds using surge with the following steps:
1. First, install Surge using npm by running the following command:
```bash
npm install --g surge
```
1. To build the static files of your site for production in the root directory of your project, run:
```bash
npm run build
```
1. Then, run this command inside the root directory of your project:
```bash
surge build/
```
First-time users of Surge would be prompted to create an account from the command line(happens only once).
Confirm that the site you want to publish is in the `build` directory, a randomly generated subdomain `*.surge.sh subdomain` is always given(which can be edited).
### Using your domain
If you have a domain name you can deploy your site using surge to your domain using the command:
```bash
surge build/ yourdomain.com
```
Your site is now deployed for free at `subdomain.surge.sh` or `yourdomain.com` depending on the method you chose.
### Setting up CNAME file
Store your domain in a CNAME file for future deployments with the following command:
```bash
echo subdomain.surge.sh > CNAME
```
You can deploy any other changes in the future with the command `surge`.

View file

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

View file

@ -0,0 +1,327 @@
---
id: docs-introduction
title: Docs Introduction
sidebar_label: Introduction
---
The docs feature provides users with a way to organize Markdown files in a hierarchical format.
## Document ID
Every document has a unique `id`. By default, a document `id` is the name of the document (without the extension) relative to the root docs directory.
For example, `greeting.md` id is `greeting` and `guide/hello.md` id is `guide/hello`.
```bash
website # Root directory of your site
└── docs
   ├── greeting.md
└── guide
└── hello.md
```
However, the **last part** of the `id` can be defined by user in the front matter. For example, if `guide/hello.md`'s content is defined as below, its final `id` is `guide/part1`.
```yml
---
id: part1
---
Lorem ipsum
```
If you want more control over the last part of the document URL, it is possible to add a `slug` (defaults to the `id`).
```yml
---
id: part1
slug: part1.html
---
Lorem ipsum
```
:::note
It is possible to use:
- absolute slugs: `slug: /mySlug`, `slug: /`...
- relative slugs: `slug: mySlug`, `slug: ./../mySlug`...
:::
## Home page docs
If you want a document to be available at the root, and have a path like `https://v2.docusaurus.io/docs/`, you can use the slug frontmatter:
```yml
---
id: my-home-doc
slug: /
---
Lorem ipsum
```
## Sidebar
To generate a sidebar to your Docusaurus site, you need to define a file that exports a sidebar object and pass that into the `@docusaurus/plugin-docs` plugin directly or via `@docusaurus/preset-classic`.
```js {8-9} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
// Sidebars filepath relative to the site dir.
sidebarPath: require.resolve('./sidebars.js'),
},
// ...
},
],
],
};
```
### Sidebar object
A sidebar object is defined like this:
```typescript
type Sidebar = {
[sidebarId: string]:
| {
[sidebarCategory: string]: SidebarItem[];
}
| SidebarItem[];
};
```
Below is an example of a sidebar object. The key `docs` is the id of the sidebar (can be renamed to something else) and `Getting Started` is a category within the sidebar. `greeting` and `doc1` are both [sidebar item](#sidebar-item).
```js title="sidebars.js"
module.exports = {
docs: {
'Getting started': ['greeting'],
Docusaurus: ['doc1'],
},
};
```
Keep in mind that EcmaScript does not guarantee `Object.keys({a,b}) === ['a','b']` (yet, this is generally true). If you don't want to rely on iteration order of JavaScript object keys for the category name, the following sidebar object is also equivalent of the above shorthand syntax.
```js title="sidebars.js"
module.exports = {
docs: [
{
type: 'category',
label: 'Getting Started',
items: ['greeting'],
},
{
type: 'category',
label: 'Docusaurus',
items: ['doc1'],
},
],
};
```
You can also have multiple sidebars for different Markdown files by adding more top-level keys to the exported object.
Example:
```js title="sidebars.js"
module.exports = {
firstSidebar: {
'Category A': ['doc1'],
},
secondSidebar: {
'Category A': ['doc2'],
'Category B': ['doc3'],
},
};
```
#### Sidebar item
As the name implies, `SidebarItem` is an item defined in a Sidebar. There are a few types we support:
- [Doc](#doc)
- [Link](#link)
- [Ref](#ref)
- [Category](#category)
#### Doc
```typescript
type SidebarItemDoc =
| string
| {
type: 'doc';
id: string;
};
```
Sidebar item type that links to a doc page. Example:
```js
{
type: 'doc',
id: 'doc1', // string - document id
}
```
Using just the [Document ID](#document-id) is perfectly valid as well, the following is equivalent to the above:
```js
'doc1'; // string - document id
```
Note that using this type will bind the linked doc to current sidebar, this means that if you access `doc1` page, the sidebar displayed will be the sidebar this item is on. For below case, `doc1` is bounded to `firstSidebar`.
```js title="sidebars.js"
module.exports = {
firstSidebar: {
'Category A': ['doc1'],
},
secondSidebar: {
'Category A': ['doc2'],
'Category B': ['doc3'],
},
};
```
#### Link
```typescript
type SidebarItemLink = {
type: 'link';
label: string;
href: string;
};
```
Sidebar item type that links to a non-document page. Example:
```js
{
type: 'link',
label: 'Custom Label', // The label that should be displayed (string).
href: 'https://example.com' // The target URL (string).
}
```
#### Ref
```typescript
type SidebarItemRef = {
type: 'ref';
id: string;
};
```
Sidebar item type that links to doc without bounding it to the sidebar. Example:
```js
{
type: 'ref',
id: 'doc1', // Document id (string).
}
```
#### Category
This is used to add hierarchies to the sidebar:
```typescript
type SidebarItemCategory = {
type: 'category';
label: string; // Sidebar label text.
items: SidebarItem[]; // Array of sidebar items.
collapsed: boolean; // Set the category to be collapsed or open by default
};
```
As an example, here's how we created the subcategory for "Docs" under "Guides" in this site:
```js title="sidebars.js"
module.exports = {
docs: {
Guides: [
'creating-pages',
{
type: 'category',
label: 'Docs',
items: ['markdown-features', 'sidebar', 'versioning'],
},
],
},
};
```
**Note**: it's possible to use the shorthand syntax to create nested categories:
```js title="sidebars.js"
module.exports = {
docs: {
Guides: [
'creating-pages',
{
Docs: ['markdown-features', 'sidebar', 'versioning'],
},
],
},
};
```
#### Collapsible categories
For sites with a sizable amount of content, we support the option to expand/collapse a category to toggle the display of its contents. Categories are collapsible by default. If you want them to be always expanded, set `themeConfig.sidebarCollapsible` to `false`:
```js {4} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
sidebarCollapsible: false,
// ...
},
};
```
#### Expanded categories by default
For docs that have collapsible categories, you may want more fine-grain control over certain categories. If you want specific categories to be always expanded, you can set `collapsed` to `false`:
```js title="sidebars.js"
module.exports = {
docs: {
Guides: [
'creating-pages',
{
type: 'category',
label: 'Docs',
collapsed: false,
items: ['markdown-features', 'sidebar', 'versioning'],
},
],
},
};
```
## Docs-only mode
If you only want the documentation feature, you can run your Docusaurus 2 site without a landing page and display your documentation page as the index page instead.
To enable docs-only mode, set the docs plugin `routeBasePath: '/'`, and use the frontmatter `slug: /` on the document that should be the index page ([more infos](#home-page-docs)).
:::caution
You should delete the existing homepage at `./src/pages/index.js`, or else there will be two files mapping to the same route!
:::
:::tip
There's also a "blog-only mode" for those who only want to use the blog feature of Docusaurus 2. You can use the same method detailed above. Follow the setup instructions on [Blog-only mode](blog.md#blog-only-mode).
:::

View file

@ -0,0 +1,322 @@
---
id: docusaurus-core
title: Docusaurus Client API
sidebar_label: Client API
---
Docusaurus provides some APIs on the clients that can be helpful to you when building your site.
## Components
### `<Head/>`
This reusable React component will manage all of your changes to the document head. It takes plain HTML tags and outputs plain HTML tags and is beginner-friendly. It is a wrapper around [React Helmet](https://github.com/nfl/react-helmet).
Usage Example:
```jsx {2,6,11}
import React from 'react';
import Head from '@docusaurus/Head';
const MySEO = () => (
<>
<Head>
<meta property="og:description" content="My custom description" />
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://mysite.com/example" />
</Head>
</>
);
```
Nested or latter components will override duplicate usages:
```jsx {2,5,8,11}
<Parent>
<Head>
<title>My Title</title>
<meta name="description" content="Helmet application" />
</Head>
<Child>
<Head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</Head>
</Child>
</Parent>
```
Outputs
```html
<head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</head>
```
### `<Link/>`
This component enables linking to internal pages as well as a powerful performance feature called preloading. Preloading is used to prefetch resources so that the resources are fetched by the time the user navigates with this component. We use an `IntersectionObserver` to fetch a low-priority request when the `<Link>` is in the viewport and then use an `onMouseOver` event to trigger a high-priority request when it is likely that a user will navigate to the requested resource.
The component is a wrapper around react-routers `<Link>` component that adds useful enhancements specific to Docusaurus. All props are passed through to react-routers `<Link>` component.
```jsx {2,7}
import React from 'react';
import Link from '@docusaurus/Link';
const Page = () => (
<div>
<p>
Check out my <Link to="/blog">blog</Link>!
</p>
<p>
{/* Note that external links still use `a` tags, but automatically opens in new tab. */}
Follow me on <a href="https://twitter.com/docusaurus">Twitter</a>!
</p>
</div>
);
```
#### `to`: string
The target location to navigate to. Example: `/docs/introduction`.
```jsx
<Link to="/courses" />
```
### `<Redirect/>`
Rendering a `<Redirect>` will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do. You can refer to [React Router's Redirect documentation](https://reacttraining.com/react-router/web/api/Redirect) for more info on available props.
Example usage:
```jsx {2,5}
import React from 'react';
import {Redirect} from '@docusaurus/router';
function Home() {
return <Redirect to="/docs/test" />;
}
```
:::note
`@docusaurus/router` implements [React Router](https://reacttraining.com/react-router/web/guides/quick-start) and supports its features.
:::
### `<BrowserOnly/>`
The `<BrowserOnly>` component accepts a `children` prop, a render function which will not be executed during the pre-rendering phase of the build process. This is useful for hiding code that is only meant to run in the browsers (e.g. where the `window`/`document` objects are being accessed). To improve SEO, you can also provide fallback content using the `fallback` prop, which will be prerendered until in the build process and replaced with the client-side only contents when viewed in the browser.
```jsx
import BrowserOnly from '@docusaurus/BrowserOnly';
function MyComponent() {
return (
<BrowserOnly
fallback={<div>The fallback content to display on prerendering</div>}>
{() => {
// Something that should be excluded during build process prerendering.
}}
</BrowserOnly>
);
}
```
## Hooks
### `useDocusaurusContext`
React hook to access Docusaurus Context. Context contains `siteConfig` object from [docusaurus.config.js](api/docusaurus.config.js.md), and some additional site metadata.
```ts
type DocusaurusPluginVersionInformation =
| {readonly type: 'package'; readonly version?: string}
| {readonly type: 'project'}
| {readonly type: 'local'}
| {readonly type: 'synthetic'};
interface DocusaurusSiteMetadata {
readonly docusaurusVersion: string;
readonly siteVersion?: string;
readonly pluginVersions: Record<string, DocusaurusPluginVersionInformation>;
}
interface DocusaurusContext {
siteConfig: DocusaurusConfig;
siteMetadata: DocusaurusSiteMetadata;
}
```
Usage example:
```jsx {5,8,9}
import React from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
const MyComponent = () => {
const {siteConfig, siteMetadata} = useDocusaurusContext();
return (
<div>
<h1>{siteConfig.title}</h1>
<div>{siteMetadata.siteVersion}</div>
<div>{siteMetadata.docusaurusVersion}</div>
</div>
);
};
```
### `useBaseUrl`
React hook to automatically prepend `baseUrl` to a string automatically. This is particularly useful if you don't want to hardcode your config's `baseUrl`. We highly recommend you to use this.
```ts
type BaseUrlOptions = {
forcePrependBaseUrl: boolean;
absolute: boolean;
};
```
Example usage:
```jsx {3,11}
import React 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>
);
}
```
### `useBaseUrlUtils`
Sometimes `useBaseUrl` is not good enough. This hook return additional utils related to your site's base url.
- `withBaseUrl`: useful if you need to add base urls to multiple urls at once
```jsx {2,5,6,7}
import React from 'react';
import {useBaseUrlUtils} from '@docusaurus/useBaseUrl';
function Component() {
const urls = ['/a', '/b'];
const {withBaseUrl} = useBaseUrlUtils();
const urlsWithBaseUrl = urls.map(withBaseUrl);
return <div className="col">{/* ... */}</div>;
}
```
### `useGlobalData()`
React hook to access Docusaurus global data created by all the plugins.
Global data is namespaced by plugin name, and plugin id.
:::info
Plugin id is only useful when a plugin is used multiple times on the same site. Each plugin instance is able to create its own global data.
:::
```ts
type GlobalData = Record<
PluginName,
Record<
PluginId, // "default" by default
any // plugin-specific data
>
>;
```
Usage example:
```jsx {2,5,6,7}
import React from 'react';
import useGlobalData from '@docusaurus/useGlobalData';
const MyComponent = () => {
const globalData = useDocusaurusContext();
const myPluginData = globalData['my-plugin']['default'];
return <div>{myPluginData.someAttribute}</div>;
};
```
:::tip
Inspect your site's global data at `./docusaurus/globalData.json`
:::
### `usePluginData(pluginName: string, pluginId?: string)`
Access global data created by a specific plugin instance.
This is the most convenient hook to access plugin global data, and should be used most of the time.
`pluginId` is optional if you don't use multi-instance plugins.
Usage example:
```jsx {2,5,6}
import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';
const MyComponent = () => {
const myPluginData = usePluginData('my-plugin');
return <div>{myPluginData.someAttribute}</div>;
};
```
### `useAllPluginInstancesData(pluginName: string)`
Access global data created by a specific plugin. Given a plugin name, it returns the data of all the plugins instances of that name, by pluginId.
Usage example:
```jsx {2,5,6,7}
import React from 'react';
import {useAllPluginInstancesData} from '@docusaurus/useGlobalData';
const MyComponent = () => {
const allPluginInstancesData = useAllPluginInstancesData('my-plugin');
const myPluginData = allPluginInstancesData['default'];
return <div>{myPluginData.someAttribute}</div>;
};
```
## Modules
### `ExecutionEnvironment`
A module which exposes a few boolean variables to check the current rendering environment. Useful if you want to only run certain code on client/server or need to write server-side rendering compatible code.
```jsx {2}
import React from 'react';
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
function MyPage() {
const location = ExecutionEnvironment.canUseDOM ? window.location.href : null;
return <div>{location}</div>;
}
```
| Field | Description |
| --- | --- |
| `ExecutionEnvironment.canUseDOM` | `true` if on client, `false` if prerendering. |
| `ExecutionEnvironment.canUseEventListeners` | `true` if on client and has `window.addEventListener`. |
| `ExecutionEnvironment.canUseIntersectionObserver` | `true` if on client and has `IntersectionObserver`. |
| `ExecutionEnvironment.canUseViewport` | `true` if on client and has `window.screen`. |

View file

@ -0,0 +1,121 @@
---
id: creating-pages
title: Creating Pages
slug: /creating-pages
---
In this section, we will learn about creating ad-hoc pages in Docusaurus using React. This is most useful for creating one-off standalone pages like a showcase page, playground page or support page.
The functionality of pages is powered by `@docusaurus/plugin-content-pages`.
You can use React components, or Markdown.
## Add a React page
Create a file `/src/pages/helloReact.js`:
```jsx title="/src/pages/helloReact.js"
import React from 'react';
import Layout from '@theme/Layout';
function Hello() {
return (
<Layout title="Hello">
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '50vh',
fontSize: '20px',
}}>
<p>
Edit <code>pages/hello.js</code> and save to reload.
</p>
</div>
</Layout>
);
}
export default Hello;
```
Once you save the file, the development server will automatically reload the changes. Now open `http://localhost:3000/helloReact`, you will see the new page you just created.
Each page doesn't come with any styling. You will need to import the `Layout` component from `@theme/Layout` and wrap your contents within that component if you want the navbar and/or footer to appear.
:::tip
You can also create TypeScript pages with the `.tsx` extension (`helloReact.tsx`).
:::
## Add a Markdown page
Create a file `/src/pages/helloMarkdown.md`:
```mdx title="/src/pages/helloMarkdown.md"
---
title: my hello page title
description: my hello page description
---
# Hello
How are you?
```
In the same way, a page will be created at `http://localhost:3000/helloMarkdown`.
Markdown pages are less flexible than React pages, because it always uses the theme layout.
Here's an [example markdown page](/examples/markdownPageExample).
:::tip
You can use the full power of React in Markdown pages too, refer to the [MDX](https://mdxjs.com/) documentation.
:::
## Routing
If you are familiar with other static site generators like Jekyll and Next, this routing approach will feel familiar to you. Any JavaScript file you create under `/src/pages/` directory will be automatically converted to a website page, following the `/src/pages/` directory hierarchy. For example:
- `/src/pages/index.js``<baseUrl>`
- `/src/pages/foo.js``<baseUrl>/foo`
- `/src/pages/foo/test.js``<baseUrl>/foo/test`
- `/src/pages/foo/index.js``<baseUrl>/foo/`
In this component-based development era, it is encouraged to co-locate your styling, markup and behavior together into components. Each page is a component, and if you need to customize your page design with your own styles, we recommend co-locating your styles with the page component in its own directory. For example, to create a "Support" page, you could do one of the following:
- Add a `/src/pages/support.js` file
- Create a `/src/pages/support/` directory and a `/src/pages/support/index.js` file.
The latter is preferred as it has the benefits of letting you put files related to the page within that directory. For example, a CSS module file (`styles.module.css`) with styles meant to only be used on the "Support" page. **Note:** this is merely a recommended directory structure and you will still need to manually import the CSS module file within your component module (`support/index.js`). By default, any Markdown or Javascript file starting with `_` will be ignored, and no routes will be created for that file (see the `exclude` option).
```sh
my-website
├── src
│ └── pages
│ ├── styles.module.css
│ ├── index.js
| ├──_ignored.js
│ └── support
│ ├── index.js
│ └── styles.module.css
.
```
:::caution
All JavaScript/TypeScript files within the `src/pages/` directory will have corresponding website paths generated for them. If you want to create reusable components into that directory, use the `exclude` option (by default, files prefixed with `_`, test files(`.test.js`) and files in `__tests__` directory are not turned into pages).
:::
## 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.
## Duplicate Routes
You may accidentally create multiple pages that are meant to be accessed on the same route. When this happens, Docusaurus will warn you about duplicate routes when you run `yarn start` or `yarn build`, but the site will still be built successfully. The page that was created last will be accessible, but it will override other conflicting pages. To resolve this issue, you should modify or remove any conflicting routes.

View file

@ -0,0 +1,895 @@
---
id: migrating-from-v1-to-v2
title: Migrating from v1 to v2
slug: /migrating-from-v1-to-v2
---
import ColorGenerator from '@site/src/components/ColorGenerator';
:::caution
This migration guide is targeted at Docusaurus users without translation and/or versioning features.
:::
This doc guides you through migrating an existing Docusaurus 1 site to Docusaurus 2.
Your Docusaurus 1 site should have the following structure:
```sh
├── docs
└── website
├── blog
├── core
│ └── Footer.js
├── package.json
├── pages
├── sidebars.json
├── siteConfig.js
└── static
```
After the migration, your Docusaurus 2 site could look like:
```sh
website
├── blog
├── docs
├── src
│ ├── components
│ ├── css
│ └── pages
├── static
├── package.json
├── sidebars.json
├── docusaurus.config.js
```
:::tip
You can use the [migration command](#migration-command) to take care of some of the migration chores.
:::
## Project setup
### `package.json`
#### Scoped package names
In Docusaurus 2, we use scoped package names:
- `docusaurus` -> `@docusaurus/core`
This provides a clear distinction between Docusaurus' official packages and community maintained packages. In another words, all Docusaurus' official packages are namespaced under `@docusaurus/`.
Meanwhile, the default doc site functionalities provided by Docusaurus 1 are now provided by `@docusaurus/preset-classic`. Therefore, we need to add this dependency as well:
```diff title="package.json"
{
dependencies: {
- "docusaurus": "^1.x.x",
+ "@docusaurus/core": "^2.0.0-alpha.48",
+ "@docusaurus/preset-classic": "^2.0.0-alpha.48",
}
}
```
:::tip
Please use the most recent Docusaurus 2 alpha version, which you can check out [here](https://www.npmjs.com/package/@docusaurus/core) (it's tagged `next`).
:::
#### CLI commands
Meanwhile, CLI commands are renamed to `docusaurus <command>` (instead of `docusaurus-command`).
The `"scripts"` section of your `package.json` should be updated as follows:
```json {3-6} title="package.json"
{
"scripts": {
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy"
// ...
}
}
```
A typical Docusaurus 2 `package.json` may look like this:
```json title="package.json"
{
"scripts": {
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy"
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.40",
"@docusaurus/preset-classic": "^2.0.0-alpha.40",
"clsx": "^1.1.1",
"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>`.
In Docusaurus 2, it is now moved to just `website/build`. Make sure that you update your deployment configuration to read the generated files from the correct `build` directory.
If you are deploying to GitHub pages, make sure to run `yarn deploy` instead of `yarn publish-gh-pages` script.
### `.gitignore`
The `.gitignore` in your `website` should contain:
```bash title=".gitignore"
# dependencies
/node_modules
# production
/build
# generated files
.docusaurus
.cache-loader
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
```
### `README`
The D1 website may have an existing README file. You can modify it to reflect the D2 changes, or copy the default [Docusaurus v2 README](https://github.com/facebook/docusaurus/blob/master/packages/docusaurus-init/templates/classic/README.md).
## Site configurations
### `docusaurus.config.js`
Rename `siteConfig.js` to `docusaurus.config.js`.
In Docusaurus 2, we split each functionality (blog, docs, pages) into plugins for modularity. Presets are bundles of plugins and for backward compatibility we built a `@docusaurus/preset-classic` preset which bundles most of the essential plugins present in Docusaurus 1.
Add the following preset configuration to your `docusaurus.config.js`.
```jsx title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
// Docs folder path relative to website dir.
path: '../docs',
// Sidebars file relative to website dir.
sidebarPath: require.resolve('./sidebars.json'),
},
// ...
},
],
],
};
```
We recommend moving the `docs` folder into the `website` folder and that is also the default directory structure in v2. [Now](https://zeit.co/now) supports [Docusaurus project deployments out-of-the-box](https://github.com/zeit/now-examples/tree/master/docusaurus) if the `docs` directory is within the `website`. It is also generally better for the docs to be within the website so that the docs and the rest of the website code are co-located within one `website` directory.
If you are migrating your Docusaurus v1 website, and there are pending documentation pull requests, you can temporarily keep the `/docs` folder to its original place, to avoid producing conflicts.
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, these configuration fields were not modified.
#### `colors`
Deprecated. We wrote a custom CSS framework for Docusaurus 2 called [Infima](https://facebookincubator.github.io/infima/) which uses CSS variables for theming. The docs are not quite ready yet and we will update here when it is. To overwrite Infima's CSS variables, create your own CSS file (e.g. `./src/css/custom.css`) and import it globally by passing it as an option to `@docusaurus/preset-classic`:
```js {7-9} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
};
```
Infima uses 7 shades of each color.
```css title="/src/css/custom.css"
/**
* You can override the default Infima variables here.
* Note: this is not a complete list of --ifm- variables.
*/
:root {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: rgb(33, 175, 144);
--ifm-color-primary-darker: rgb(31, 165, 136);
--ifm-color-primary-darkest: rgb(26, 136, 112);
--ifm-color-primary-light: rgb(70, 203, 174);
--ifm-color-primary-lighter: rgb(102, 212, 189);
--ifm-color-primary-lightest: rgb(146, 224, 208);
}
```
We recommend using [ColorBox](https://www.colorbox.io/) to find the different shades of colors for your chosen primary color.
Alteratively, use the following tool to generate the different shades for your website and copy the variables into `src/css/custom.css`.
<ColorGenerator/>
#### `footerIcon`, `copyright`, `ogImage`, `twitterImage`, `docsSideNavCollapsible`
Site meta info such as assets, SEO, copyright info are now handled by themes. To customize them, use the `themeConfig` field in your `docusaurus.config.js`:
```jsx title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
footer: {
logo: {
alt: 'Facebook Open Source Logo',
src: 'https://docusaurus.io/img/oss_logo.png',
href: 'https://opensource.facebook.com/',
},
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`, // You can also put own HTML here.
},
image: 'img/docusaurus.png',
// Equivalent to `docsSideNavCollapsible`.
sidebarCollapsible: false,
// ...
},
};
```
#### `headerIcon`, `headerLinks`
In Docusaurus 1, header icon and header links were root fields in `siteConfig`:
```js title="siteConfig.js"
headerIcon: 'img/docusaurus.svg',
headerLinks: [
{ doc: "doc1", label: "Getting Started" },
{ page: "help", label: "Help" },
{ href: "https://github.com/", label: "GitHub" },
{ blog: true, label: "Blog" },
],
```
Now, these two fields are both handled by the theme:
```jsx {6-19} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
title: 'Docusaurus',
logo: {
alt: 'Docusaurus Logo',
src: 'img/docusaurus.svg',
},
items: [
{to: 'docs/doc1', label: 'Getting Started', position: 'left'},
{to: 'help', label: 'Help', position: 'left'},
{
href: 'https://github.com/',
label: 'GitHub',
position: 'right',
},
{to: 'blog', label: 'Blog', position: 'left'},
],
},
// ...
},
};
```
#### `algolia`
```jsx {4-8} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
algolia: {
apiKey: '47ecd3b21be71c5822571b9f59e52544',
indexName: 'docusaurus-2',
algoliaOptions: { //... },
},
// ...
},
};
```
#### `blogSidebarCount`
Deprecated. Pass it as a blog option to `@docusaurus/preset-classic` instead:
```jsx {8} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
blog: {
postsPerPage: 10,
},
// ...
},
],
],
};
```
#### `cname`
Deprecated. Create a `CNAME` file in your `static` folder instead with your custom domain. Files in the `static` folder will be copied into the root of the `build` folder during execution of the build command.
#### `customDocsPath`, `docsUrl`, `editUrl`, `enableUpdateBy`, `enableUpdateTime`
**BREAKING**: `editUrl` should point to (website) docusaurus project instead of `docs` directory.
Deprecated. Pass it as an option to `@docusaurus/preset-classic` docs instead:
```jsx {8-20} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
// Equivalent to `customDocsPath`.
path: 'docs',
// Equivalent to `editUrl` but should point to `website` dir instead of `website/docs`.
editUrl: 'https://github.com/facebook/docusaurus/edit/master/website',
// Equivalent to `docsUrl`.
routeBasePath: 'docs',
// Remark and Rehype plugins passed to MDX. Replaces `markdownOptions` and `markdownPlugins`.
remarkPlugins: [],
rehypePlugins: [],
// Equivalent to `enableUpdateBy`.
showLastUpdateAuthor: true,
// Equivalent to `enableUpdateTime`.
showLastUpdateTime: true,
},
// ...
},
],
],
};
```
#### `gaTrackingId`
```jsx {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
googleAnalytics: {
trackingID: 'UA-141789564-1',
},
// ...
},
};
```
#### `gaGtag`
```jsx {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
gtag: {
trackingID: 'UA-141789564-1',
},
// ...
},
};
```
### Removed fields
The following fields are all deprecated, you may remove from your configuration file.
- `blogSidebarTitle`
- `cleanUrl` - Clean URL is used by default now.
- `defaultVersionShown` - Versioning is not ported yet. You'd be unable to migration to Docusaurus 2 if you are using versioning. Stay tuned.
- `disableHeaderTitle`
- `disableTitleTagline`
- `docsSideNavCollapsible` is available at `themeConfig.sidebarCollapsible`, and this is turned on by default now.
- `facebookAppId`
- `facebookComments`
- `facebookPixelId`
- `fonts`
- `highlight` - We now use [Prism](https://prismjs.com/) instead of [highlight.js](https://highlightjs.org/).
- `markdownOptions` - We use MDX in v2 instead of Remarkable. Your markdown options have to be converted to Remark/Rehype plugins.
- `markdownPlugins` - We use MDX in v2 instead of Remarkable. Your markdown plugins have to be converted to Remark/Rehype plugins.
- `manifest`
- `noIndex`
- `onPageNav` - This is turned on by default now.
- `separateCss` - It can imported in the same manner as `custom.css` mentioned above.
- `scrollToTop`
- `scrollToTopOptions`
- `translationRecruitingLink`
- `twitter`
- `twitterUsername`
- `useEnglishUrl`
- `users`
- `usePrism` - We now use [Prism](https://prismjs.com/) instead of [highlight.js](https://highlightjs.org/)
- `wrapPagesHTML`
We intend to implement many of the deprecated config fields as plugins in future. Help will be appreciated!
## Urls
In v1, all pages were available with or without the `.html` extension.
For example, these 2 pages exist:
- [https://docusaurus.io/docs/en/installation](https://docusaurus.io/docs/en/installation)
- [https://docusaurus.io/docs/en/installation.html](https://docusaurus.io/docs/en/installation.html)
If [`cleanUrl`](https://docusaurus.io/docs/en/site-config#cleanurl-boolean) was:
- `true`: links would target `/installation`
- `false`: links would target `/installation.html`
In v2, by default, the canonical page is `/installation`, and not `/installation.html`.
If you had `cleanUrl: false` in v1, it's possible that people published links to `/installation.html`.
For SEO reasons, and avoiding breaking links, you should configure server-side redirect rules on your hosting provider.
As an escape hatch, you could use [@docusaurus/plugin-client-redirects](./using-plugins.md#docusaurusplugin-client-redirects) to create client-side redirects from `/installation.html` to `/installation`.
```js
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
fromExtensions: ['html'],
},
],
],
};
```
If you want to keep the `.html` extension as the canonical url of a page, docs can declare a `slug: installation.html` frontmatter.
## Components
### Sidebar
In previous version, nested sidebar category is not allowed and sidebar category can only contain doc id. However, v2 allows infinite nested sidebar and we have many types of [Sidebar Item](docs.md#sidebar-item) other than document.
You'll have to migrate your sidebar if it contains category type. Rename `subcategory` to `category` and `ids` to `items`.
```diff title="sidebars.json"
{
- type: 'subcategory',
+ type: 'category',
label: 'My Example Subcategory',
+ items: ['doc1'],
- ids: ['doc1']
},
```
### Footer
`website/core/Footer.js` is no longer needed. If you want to modify the default footer provided by Docusaurus, [swizzle](using-themes.md#swizzling-theme-components) it:
```bash npm2yarn
npm run swizzle @docusaurus/theme-classic Footer
```
This will copy the current `<Footer />` component used by the theme to a `src/theme/Footer` directory under the root of your site, you may then edit this component for customization.
Do not swizzle the Footer just to add the logo on the left. The logo is intentionally removed in v2 and moved to the bottom. Just configure the footer in `docusaurus.config.js` with `themeConfig.footer`:
```js
module.exports = {
themeConfig: {
footer: {
logo: {
alt: 'Facebook Open Source Logo',
src: 'img/oss_logo.png',
href: 'https://opensource.facebook.com',
},
},
},
};
```
### Pages
Please refer to [creating pages](guides/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.
In Docusaurus v1, pages received the `siteConfig` object as props.
In Docusaurus v2, get the `siteConfig` object from `useDocusaurusContext` instead.
In v2, you have to apply the theme layout around each page. The Layout component takes metadata props (`permalink` is important, as it defines the canonical url of your page).
`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).
You can migrate CommonJS to ES6 imports/exports.
Here's a typical Docusaurus v2 page:
```jsx
import React from 'react';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
import Layout from '@theme/Layout';
const MyPage = () => {
const {siteConfig} = useDocusaurusContext();
return (
<Layout
permalink="/"
title={siteConfig.title}
description={siteConfig.tagline}>
<div className="hero text--center">
<div className="container ">
<div className="padding-vert--md">
<h1 className="hero__title">{siteConfig.title}</h1>
<p className="hero__subtitle">{siteConfig.tagline}</p>
</div>
<div>
<Link
to={useBaseUrl('/docs/get-started')}
className="button button--lg button--outline button--primary">
Get started
</Link>
</div>
</div>
</div>
</Layout>
);
};
export default MyPage;
```
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.
Frontmatter is parsed by [gray-matter](https://github.com/jonschlinkert/gray-matter). If your frontmatter use special characters like `:`, you now need to quote it: `title: Part 1: my part1 title` -> `title: Part 1: "my part1 title"`.
**Tips**: You might want to use some online tools like [HTML to JSX](https://transform.tools/html-to-jsx) to make the migration easier.
### Language-specific code tabs
Refer to the [multi-language support code blocks](markdown-features.mdx#multi-language-support-code-blocks) section.
### Front matter
The Docusaurus front matter fields for the blog have been changed from camelCase to snake_case to be consistent with the docs.
The fields `authorFBID` and `authorTwitter` have been deprecated. They are only used for generating the profile image of the author which can be done via the `author_image_url` field.
## Test your site
After migration, your folder structure should look like this:
```sh
my-project
├── docs
└── website
├── blog
├── src
│ ├── css
│ │ └── custom.css
│ └── pages
│ └── index.js
├── package.json
├── sidebars.json
├── .gitignore
├── docusaurus.config.js
└── static
```
Start the development server and fix any errors:
```bash
cd website
yarn start
```
## Migration command
The migration command automatically migrates your v1 website to a v2 website.
The migration command migrates:
- Site configurations (from `siteConfig.js` to `docusaurus.config.js`)
- `package.json`
- `sidebars.json`
- `/docs`
- `/blog`
- `/static`
- `versioned_sidebar.json` and `/versioned_docs` if your site uses versioning
:::info
Manual tweaking is still required after using the migration command. You still need to migrate your [footer](#footer), [pages](#pages) and [content](#content).
:::
To use the migration command, follow these steps:
1. Before using the migration command, ensure that `/docs`, `/blog`, `/static`, `sidebars.json`, `siteConfig.js`, `package.json` follow the [structure](#) shown at the start of this page.
2. To migrate your v1 website, run the migration command with the appropriate filesystem paths:
```
// migration command format
npx @docusaurus/migrate migrate <v1 website directory> <desired v2 website directory>
// example
npx @docusaurus/migrate migrate ./v1-website ./v2-website
```
3. To view your new website locally, go into your v2 website's directory and start your development server.
```bash
cd ./v2-website
yarn install
yarn start
```
#### Options
You can add option flags to the migration command to automatically migrate markdown content and pages to v2. It is likely that you will still need to make some manual changes to achieve your desired result.
| Name | Description |
| -------- | ------------------------------------------------------ |
| `--mdx` | Add this flag to convert markdown to mdx automatically |
| `--page` | Add this flag to migrate pages automatically |
```
// example using options
npx docusaurus-migrate migrate --mdx --page ./v1-website ./v2-website
```
:::danger
The migration of pages and MDX is still a work in progress.
We recommend you to try to run the pages without these options, commit, and then try to run the migration again with the --page and --mdx options.
This way, you'd be able to easily inspect and fix the diff.
:::
## Example migration PRs
You might want to refer to our migration PRs for [Create React App](https://github.com/facebook/create-react-app/pull/7785) and [Flux](https://github.com/facebook/flux/pull/471) as examples of how a migration for a basic Docusaurus v1 site can be done.
## Support
For any questions, you can ask in the [`#docusaurus-1-to-2-migration` Discord channel](https://discordapp.com/invite/kYaNd6V). Feel free to tag [@yangshun](https://github.com/yangshun) in any migration PRs if you would like us to have a look.
---
## Versioned Site
:::caution
The versioning feature is a work in progress! Although we've implemented docs versioning since `2.0.0-alpha.37`, we'd like to test it out for v2 users first before we recommend v1 users to migrate to v2. There are some changes in how v2 versioning works compared to v1. In the future, we might create a script to migrate your versioned docs easier. However, if you are adventurous enough to manually migrate, feel free to do so. Be warned though, the manual migration requires lot of work.
:::
Read up https://v2.docusaurus.io/blog/2018/09/11/Towards-Docusaurus-2#versioning first for problems in v1's approach.
### Migrate your `versioned_docs` front matter
Unlike v1, The markdown header for each versioned doc is no longer altered by using `version-${version}-${original_id}` as the value for the actual id field. See scenario below for better explanation.
For example, if you have a `docs/hello.md`.
```md
---
id: hello
title: Hello, World !
---
Hi, Endilie here :)
```
When you cut a new version 1.0.0, in Docusaurus v1, `website/versioned_docs/version-1.0.0/hello.md` looks like this:
```md
---
id: version-1.0.0-hello
title: Hello, World !
original_id: hello
---
Hi, Endilie here :)
```
In comparison, Docusaurus 2 `website/versioned_docs/version-1.0.0/hello.md` looks like this (exactly same as original)
```md
---
id: hello
title: Hello, World !
---
Hi, Endilie here :)
```
Since we're going for snapshot and allow people to move (and edit) docs easily inside version. The `id` frontmatter is no longer altered and will remain the same. Internally, it is set as `version-${version}/${id}`.
Essentially, here are the necessary changes in each versioned_docs file:
```diff {2-3,5}
---
- id: version-1.0.0-hello
+ id: hello
title: Hello, World !
- original_id: hello
---
Hi, Endilie here :)
```
### Migrate your `versioned_sidebars`
- Refer to `versioned_docs` id as `version-${version}/${id}` (v2) instead of `version-${version}-${original_id}` (v1).
Because in v1 there is a good chance someone created a new file with front matter id `"version-${version}-${id}"` that can conflict with `versioned_docs` id.
For example, Docusaurus 1 can't differentiate `docs/xxx.md`
```md
---
id: version-1.0.0-hello
---
Another content
```
vs `website/versioned_docs/version-1.0.0/hello.md`
```md
---
id: version-1.0.0-hello
title: Hello, World !
original_id: hello
---
Hi, Endilie here :)
```
Since we don't allow `/` in v1 & v2 for frontmatter, conflicts are less likely to occur.
So v1 users need to migrate their versioned_sidebars file
Example `versioned_sidebars/version-1.0.0-sidebars.json`:
```diff {2-3,5-6,9-10} title="versioned_sidebars/version-1.0.0-sidebars.json"
{
+ "version-1.0.0/docs": {
- "version-1.0.0-docs": {
"Test": [
+ "version-1.0.0/foo/bar",
- "version-1.0.0-foo/bar",
],
"Guides": [
+ "version-1.0.0/hello",
- "version-1.0.0-hello"
]
}
}
```
### Populate your `versioned_sidebars` and `versioned_docs`
In v2, we use snapshot approach for documentation versioning. **Every versioned docs does not depends on other version**. It is possible to have `foo.md` in `version-1.0.0` but it doesn't exist in `version-1.2.0`. This is not possible in previous version due to Docusaurus v1 fallback functionality (https://docusaurus.io/docs/en/versioning#fallback-functionality).
For example, if your `versions.json` looks like this in v1
```json title="versions.json"
["1.1.0", "1.0.0"]
```
Docusaurus v1 creates versioned docs **if and only if the doc content is different**. Your docs structure might look like this if the only doc changed from v1.0.0 to v1.1.0 is `hello.md`.
```shell
website
├── versioned_docs
│ ├── version-1.1.0
│ │ └── hello.md
│ └── version-1.0.0
│ ├── foo
│ │ └── bar.md
│ └── hello.md
├── versioned_sidebars
│ └── version-1.0.0-sidebars.json
```
In v2, you have to populate the missing `versioned_docs` and `versioned_sidebars` (with the right frontmatter and id reference too).
```shell {3-5,12}
website
├── versioned_docs
│ ├── version-1.1.0
│ │ ├── foo
│ │ │ └── bar.md
│ │ └── hello.md
│ └── version-1.0.0
│ ├── foo
│ │ └── bar.md
│ └── hello.md
├── versioned_sidebars
│ ├── version-1.1.0-sidebars.json
│ └── version-1.0.0-sidebars.json
```
### Convert style attributes to style objects in MDX
Docusaurus 2 uses JSX for doc files. If you have any style attributes in your Docusaurus 1 docs, convert them to style objects, like this:
```diff
---
id: demo
title: Demo
---
## Section
hello world
- pre style="background: black">zzz</pre>
+ pre style={{background: 'black'}}>zzz</pre>
```

View file

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

View file

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

View file

@ -0,0 +1,640 @@
---
id: lifecycle-apis
title: Lifecycle APIs
---
:::caution
This section is a work in progress.
:::
Lifecycle APIs are shared by Themes and Plugins.
## `validateOptions({options,validate})`
Return validated and normalized options for the plugin. This method is called before the plugin is initialized.You must return options since the returned options will be passed to plugin during intialization.
### `options`
`validateOptions` is called with `options` passed to plugin for validation and normalization.
### `validate`
`validateOptions` is called with `validate` function which takes a **[Joi](https://www.npmjs.com/package/@hapi/joi)** schema and options as argument, returns validated and normalized options. `validate` will automatically handle error and validation config.
:::tip
[Joi](https://www.npmjs.com/package/@hapi/joi) is recommended for validation and normalization of options.
:::
If you don't use **[Joi](https://www.npmjs.com/package/@hapi/joi)** for validation you can throw an Error in case of invalid options and return options in case of success.
```js {8-11} title="my-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
// rest of methods
};
};
module.exports.validateOptions = ({options, validate}) => {
const validatedOptions = validate(myValidationSchema, options);
return validationOptions;
};
```
You can also use ES modules style exports.
```ts {8-11} title="my-plugin/src/index.ts"
export default function (context, options) {
return {
name: 'docusaurus-plugin',
// rest of methods
};
}
export function validateOptions({options, validate}) {
const validatedOptions = validate(myValidationSchema, options);
return validationOptions;
}
```
## `validateThemeConfig({themeConfig,validate})`
Return validated and normalized configuration for the theme.
### `themeConfig`
`validateThemeConfig` is called with `themeConfig` provided in `docusaurus.config.js` for validation and normalization.
### `validate`
`validateThemeConfig` is called with `validate` function which takes a **[Joi](https://www.npmjs.com/package/@hapi/joi)** schema and `themeConfig` as argument, returns validated and normalized options. `validate` will automatically handle error and validation config.
:::tip
[Joi](https://www.npmjs.com/package/@hapi/joi) is recommended for validation and normalization of theme config.
:::
If you don't use **[Joi](https://www.npmjs.com/package/@hapi/joi)** for validation you can throw an Error in case of invalid options.
```js {8-11} title="my-theme/src/index.js"
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
// rest of methods
};
};
module.exports.validateThemeConfig = ({themeConfig, validate}) => {
const validatedThemeConfig = validate(myValidationSchema, options);
return validatedThemeConfig;
};
```
You can also use ES modules style exports.
```ts {8-11} title="my-theme/src/index.ts"
export default function (context, options) {
return {
name: 'docusaurus-plugin',
// rest of methods
};
}
export function validateThemeConfig({themeConfig, validate}) {
const validatedThemeConfig = validate(myValidationSchema, options);
return validatedThemeConfig;
}
```
## `getPathsToWatch()`
Specifies the paths to watch for plugins and themes. The paths are watched by the dev server so that the plugin lifecycles are reloaded when contents in the watched paths change. Note that the plugins and themes modules are initially called with `context` and `options` from Node, which you may use to find the necessary directory information about the site.
Example:
```js {5-7} title="docusaurus-plugin/src/index.js"
const path = require('path');
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
getPathsToWatch() {
const contentPath = path.resolve(context.siteDir, options.path);
return [`${contentPath}/**/*.{ts,tsx}`];
},
};
};
```
## `async loadContent()`
Plugins should use this lifecycle to fetch from data sources (filesystem, remote API, headless CMS, etc) or doing some server processing.
For example, this plugin below return a random integer between 1 to 10 as content;
```js {5-6} title="docusaurus-plugin/src/index.js"
const path = require('path');
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
async loadContent() {
return 1 + Math.floor(Math.random() * 10);
},
};
};
```
## `async contentLoaded({content, actions})`
Plugins should use the data loaded in `loadContent` and construct the pages/routes that consume the loaded data (optional).
### `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 function to help you create static data (generally json or string), that you can provide to your routes as props.
For example, this plugin below create a `/friends` page which display `Your friends are: Yangshun, Sebastien`:
```jsx title="website/src/components/Friends.js"
import React from 'react';
export default function FriendsComponent({friends}) {
return <div>Your friends are {friends.join(',')}</div>;
}
```
```js {4-23} title="docusaurus-friends-plugin/src/index.js"
export default function friendsPlugin(context, options) {
return {
name: 'docusaurus-friends-plugin',
async contentLoaded({content, actions}) {
const {createData, addRoute} = actions;
// Create friends.json
const friends = ['Yangshun', 'Sebastien'];
const friendsJsonPath = await createData(
'friends.json',
JSON.stringify(friends),
);
// Add the '/friends' routes, and ensure it receives the friends props
addRoute({
path: '/friends',
component: '@site/src/components/Friends.js',
modules: {
// propName -> json file path
friends: friendsJsonPath,
},
exact: true,
});
},
};
}
```
- `setGlobalData(data: any): void`
This function permits to create some global plugin data, that can be read from any page, including the pages created by other plugins, and your theme layout.
This data become accessible to your client-side/theme code, through the [`useGlobalData`](./docusaurus-core.md#useglobaldata) and [`usePluginData`](./docusaurus-core.md#useplugindatapluginname-string-pluginid-string)
One this data is created, you can access it with the global data hooks APIs
:::caution
Global data is... global: its size affects the loading time of all pages of your site, so try to keep it small.
Prefer `createData` and page-specific data whenever possible.
:::
For example, this plugin below create a `/friends` page which display `Your friends are: Yangshun, Sebastien`:
```jsx title="website/src/components/Friends.js"
import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';
export default function FriendsComponent() {
const {friends} = usePluginData('my-friends-plugin');
return <div>Your friends are {friends.join(',')}</div>;
}
```
```js {4-14} title="docusaurus-friends-plugin/src/index.js"
export default function friendsPlugin(context, options) {
return {
name: 'docusaurus-friends-plugin',
async contentLoaded({content, actions}) {
const {setGlobalData, addRoute} = actions;
// Create friends global data
setGlobalData({friends: ['Yangshun', 'Sebastien']});
// Add the '/friends' routes
addRoute({
path: '/friends',
component: '@site/src/components/Friends.js',
exact: true,
});
},
};
}
```
## `configureWebpack(config, isServer, utils)`
Modifies the internal webpack config. If the return value is a JavaScript object, it will be merged into the final config using [`webpack-merge`](https://github.com/survivejs/webpack-merge). If it is a function, it will be called and receive `config` as the first argument and an `isServer` flag as the argument argument.
### `config`
`configureWebpack` is called with `config` generated according to client/server build. You may treat this as the base config to be merged with.
### `isServer`
`configureWebpack` will be called both in server build and in client build. The server build receives `true` and the client build receives `false` as `isServer`.
### `utils`
The initial call to `configureWebpack` also receives a util object consists of three functions:
- `getStyleLoaders(isServer: boolean, cssOptions: {[key: string]: any}): Loader[]`
- `getCacheLoader(isServer: boolean, cacheOptions?: {}): Loader | null`
- `getBabelLoader(isServer: boolean, babelOptions?: {}): Loader`
You may use them to return your webpack configures conditionally.
For example, this plugin below modify the webpack config to transpile `.foo` file.
```js {4-11} title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'custom-docusaurus-plugin',
configureWebpack(config, isServer, utils) {
const {getCacheLoader} = utils;
return {
module: {
rules: [
{
test: /\.foo$/,
use: [getCacheLoader(isServer), 'my-custom-webpack-loader'],
},
],
},
};
},
};
};
```
### Merge strategy
We merge the Webpack configuration parts of plugins into the global Webpack config using [webpack-merge](https://github.com/survivejs/webpack-merge).
It is possible to specify the merge strategy. For example, if you want a webpack rule to be prepended instead of appended:
```js {4-11} title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'custom-docusaurus-plugin',
configureWebpack(config, isServer, utils) {
return {
mergeStrategy: {'module.rules': 'prepend'},
module: {rules: [myRuleToPrepend]},
};
},
};
};
```
Read the [webpack-merge strategy doc](https://github.com/survivejs/webpack-merge#merging-with-strategies) for more details.
## `postBuild(props)`
Called when a (production) build finishes.
```ts
type Props = {
siteDir: string;
generatedFilesDir: string;
siteConfig: DocusaurusConfig;
outDir: string;
baseUrl: string;
headTags: string;
preBodyTags: string;
postBodyTags: string;
routesPaths: string[];
plugins: Plugin<any>[];
};
```
Example:
```js {4-9} title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
async postBuild({siteConfig = {}, routesPaths = [], outDir}) {
// Print out to console all the rendered routes.
routesPaths.map((route) => {
console.log(route);
});
},
};
};
```
## `extendCli(cli)`
Register an extra command to enhance the CLI of docusaurus. `cli` is [commander](https://www.npmjs.com/package/commander) object.
Example:
```js {4-11} title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
extendCli(cli) {
cli
.command('roll')
.description('Roll a random number between 1 and 1000')
.action(() => {
console.log(Math.floor(Math.random() * 1000 + 1));
});
},
};
};
```
## `injectHtmlTags()`
Inject head and/or body HTML tags to Docusaurus generated HTML.
```typescript
function injectHtmlTags(): {
headTags?: HtmlTags;
preBodyTags?: HtmlTags;
postBodyTags?: HtmlTags;
};
type HtmlTags = string | HtmlTagObject | (string | HtmlTagObject)[];
interface HtmlTagObject {
/**
* Attributes of the HTML tag
* E.g. `{'disabled': true, 'value': 'demo', 'rel': 'preconnect'}`
*/
attributes?: {
[attributeName: string]: string | boolean;
};
/**
* The tag name e.g. `div`, `script`, `link`, `meta`
*/
tagName: string;
/**
* The inner HTML
*/
innerHTML?: string;
}
```
Example:
```js {4-28} title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) {
return {
name: 'docusaurus-plugin',
injectHtmlTags() {
return {
headTags: [
{
tagName: 'link',
attributes: {
rel: 'preconnect',
href: 'https://www.github.com',
},
},
],
preBodyTags: [
{
tagName: 'script',
attributes: {
charset: 'utf-8',
src: '/noflash.js',
},
},
],
postBodyTags: [`<div> This is post body </div>`],
};
},
};
};
```
## `getThemePath()`
Returns the path to the directory where the theme components can be found. When your users calls `swizzle`, `getThemePath` is called and its returned path is used to find your theme components.
If you use the folder directory above, your `getThemePath` can be:
```js {6-8} title="my-theme/src/index.js"
const path = require('path');
module.exports = function (context, options) {
return {
name: 'name-of-my-theme',
getThemePath() {
return path.resolve(__dirname, './theme');
},
};
};
```
## `getTypeScriptThemePath()`
Similar to `getThemePath()`, it should return the path to the directory where the source code of TypeScript theme components can be found. Theme components under this path will **not** be resolved by Webpack. Therefore, it is not a replacement of `getThemePath()`. Instead, this path is purely for swizzling TypeScript theme components.
If you want to support TypeScript component swizzling for your theme, you can make the path returned by `getTypeScriptThemePath()` be your source directory, and make path returned by `getThemePath()` be the compiled JavaScript output.
Example:
```js {6-13} title="my-theme/src/index.js"
const path = require('path');
module.exports = function (context, options) {
return {
name: 'name-of-my-theme',
getThemePath() {
// Where compiled JavaScript output lives
return path.join(__dirname, '..', 'lib', 'theme');
},
getTypeScriptThemePath() {
// Where TypeScript source code lives
return path.resolve(__dirname, './theme');
},
};
};
```
## `getSwizzleComponentList()`
Return a list of stable component that are considered as safe for swizzling. These components will be listed in swizzle component without `--danger`. All the components are considers unstable by default. If an empty array is returned then all components are considered unstable, if `undefined` is returned then all component are considered stable.
```js {0-12} title="my-theme/src/index.js"
const swizzleAllowedComponents = [
'CodeBlock',
'DocSidebar',
'Footer',
'NotFound',
'SearchBar',
'hooks/useTheme',
'prism-include-languages',
];
module.exports.getSwizzleComponentList = () => swizzleAllowedComponents;
```
## `getClientModules()`
Returns an array of paths to the modules that are to be imported in the client bundle. These modules are imported globally before React even renders the initial UI.
As an example, to make your theme load a `customCss` object from `options` passed in by the user:
```js {7-9} title="my-theme/src/index.js"
const path = require('path');
module.exports = function (context, options) {
const {customCss} = options || {};
return {
name: 'name-of-my-theme',
getClientModules() {
return [customCss];
},
};
};
```
<!--
For example, the in docusaurus-plugin-content-docs:
In loadContent, it loads the doc Markdown files based on the specified directory in options (defaulting to docs).
In contentLoaded, for each doc Markdown file, a route is created: /doc/installation, /doc/getting-started, etc.
-->
## Example
Here's a mind model for a presumptuous plugin implementation.
```jsx
const DEFAULT_OPTIONS = {
// Some defaults.
};
// A JavaScript function that returns an object.
// `context` is provided by Docusaurus. Example: siteConfig can be accessed from context.
// `opts` is the user-defined options.
module.exports = function (context, opts) {
// Merge defaults with user-defined options.
const options = {...DEFAULT_OPTIONS, ...options};
return {
// A compulsory field used as the namespace for directories to cache
// the intermediate data for each plugin.
// If you're writing your own local plugin, you will want it to
// be unique in order not to potentially conflict with imported plugins.
// A good way will be to add your own project name within.
name: 'docusaurus-my-project-cool-plugin',
async loadContent() {
// The loadContent hook is executed after siteConfig and env has been loaded.
// You can return a JavaScript object that will be passed to contentLoaded hook.
},
async contentLoaded({content, actions}) {
// The contentLoaded hook is done after loadContent hook is done.
// `actions` are set of functional API provided by Docusaurus (e.g. addRoute)
},
async postBuild(props) {
// After docusaurus <build> finish.
},
// TODO
async postStart(props) {
// docusaurus <start> finish
},
// TODO
afterDevServer(app, server) {
// https://webpack.js.org/configuration/dev-server/#devserverbefore
},
// TODO
beforeDevServer(app, server) {
// https://webpack.js.org/configuration/dev-server/#devserverafter
},
configureWebpack(config, isServer) {
// Modify internal webpack config. If returned value is an Object, it
// will be merged into the final config using webpack-merge;
// If the returned value is a function, it will receive the config as the 1st argument and an isServer flag as the 2nd argument.
},
getPathsToWatch() {
// Paths to watch.
},
getThemePath() {
// Returns the path to the directory where the theme components can
// be found.
},
getClientModules() {
// Return an array of paths to the modules that are to be imported
// in the client bundle. These modules are imported globally before
// React even renders the initial UI.
},
extendCli(cli) {
// Register an extra command to enhance the CLI of Docusaurus
},
injectHtmlTags() {
// Inject head and/or body HTML tags.
},
};
};
```

File diff suppressed because it is too large Load diff

View file

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

View file

@ -0,0 +1,128 @@
---
id: search
title: Search
keywords:
- algolia
- search
---
Docusaurus' own `@docusaurus/preset-classic` supports a search integration.
There are two main options, you can use [Algolia DocSearch](https://docsearch.algolia.com) 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`. **[Apply for DocSearch](https://docsearch.algolia.com/apply/)** to get your Algolia index and API key.
```jsx title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
// ...
// highlight-start
algolia: {
apiKey: 'YOUR_API_KEY',
indexName: 'YOUR_INDEX_NAME',
searchParameters: {}, // Optional (if provided by Algolia)
},
// highlight-end
},
};
```
:::info
The `searchParameters` option used to be named `algoliaOptions` in Docusaurus v1.
:::
### Styling your Algolia search
By default, DocSearch comes with a fine-tuned theme that was designed for accessibility, making sure that colors and contrasts respect standards.
Still, you can reuse the [Infima CSS variables](styling-layout#styling-your-site-with-infima) from Docusaurus to style DocSearch by editing the `/src/css/custom.css` file.
```css title="/src/css/custom.css"
html[data-theme='light'] .DocSearch {
/* --docsearch-primary-color: var(--ifm-color-primary); */
/* --docsearch-text-color: var(--ifm-font-color-base); */
--docsearch-muted-color: var(--ifm-color-secondary-darkest);
--docsearch-container-background: rgba(94, 100, 112, 0.7);
/* Modal */
--docsearch-modal-background: var(--ifm-color-secondary-lighter);
/* Search box */
--docsearch-searchbox-background: var(--ifm-color-secondary);
--docsearch-searchbox-focus-background: var(--ifm-color-white);
/* Hit */
--docsearch-hit-color: var(--ifm-font-color-base);
--docsearch-hit-active-color: var(--ifm-color-white);
--docsearch-hit-background: var(--ifm-color-white);
/* Footer */
--docsearch-footer-background: var(--ifm-color-white);
}
html[data-theme='dark'] .DocSearch {
--docsearch-text-color: var(--ifm-font-color-base);
--docsearch-muted-color: var(--ifm-color-secondary-darkest);
--docsearch-container-background: rgba(47, 55, 69, 0.7);
/* Modal */
--docsearch-modal-background: var(--ifm-background-color);
/* Search box */
--docsearch-searchbox-background: var(--ifm-background-color);
--docsearch-searchbox-focus-background: var(--ifm-color-black);
/* Hit */
--docsearch-hit-color: var(--ifm-font-color-base);
--docsearch-hit-active-color: var(--ifm-color-white);
--docsearch-hit-background: var(--ifm-color-emphasis-100);
/* Footer */
--docsearch-footer-background: var(--ifm-background-surface-color);
--docsearch-key-gradient: linear-gradient(
-26.5deg,
var(--ifm-color-emphasis-200) 0%,
var(--ifm-color-emphasis-100) 100%
);
}
```
### Customizing the Algolia search behavior
<!-- TODO: update options link once the documentation is available on the DocSearch website -->
Algolia DocSearch supports a [list of options](https://autocomplete-experimental.netlify.app/docs/DocSearchModal#reference) that you can pass to the `algolia` field in the `docusaurus.config.js` file.
```js title="docusaurus.config.js"
module.exports = {
themeConfig: {
// ...
algolia: {
apiKey: 'YOUR_API_KEY',
indexName: 'YOUR_INDEX_NAME',
// Options...
},
},
};
```
### Editing the Algolia search component
If you prefer to edit the Algolia search 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](#editing-the-algolia-search-component) and create your own search component from there.

View file

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

View file

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

View file

@ -0,0 +1,176 @@
---
id: theme-bootstrap
title: '@docusaurus/theme-bootstrap'
---
:::caution
This section is a work in progress.
:::
## Hooks
### `useLogo`
React hook to access the logo asset.
Usage example:
```jsx
import React from 'react';
// highlight-next-line
import useLogo from '@theme/hooks/useLogo';
const Example = () => {
// highlight-next-line
const {logoLink, logoLinkProps, logoImageUrl, logoAlt} = useLogo();
return (
<Link to={logoLink} {...logoLinkProps}>
{logoImageUrl != null && <img src={logoImageUrl} alt={logoAlt} />}
</Link>
);
};
```
## Navbar
### Navbar title & logo
You can add a logo and title to the navbar via `themeConfig.navbar`. Logo can be placed in [static folder](static-assets.md). Logo URL is set to base URL of your site by default. Although you can specify your own URL for the logo, if it is an external link, it will open in a new tab. In addition, you can override a value for the target attribute of logo link, it can come in handy if you are hosting docs website in a subdirectory of your main website, and in which case you probably do not need a link in the logo to the main website will open in a new tab.
```js {5-11} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
title: 'Site Title',
logo: {
alt: 'Site Logo',
src: 'img/logo.svg',
href: 'https://v2.docusaurus.io/', // Default to `siteConfig.baseUrl`.
target: '_self', // By default, this value is calculated based on the `href` attribute (the external link will open in a new tab, all others in the current one).
},
},
// ...
},
};
```
### Navbar links
You can add links to the navbar via `themeConfig.navbar.links`:
```js {5-15} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
links: [
{
// Client-side routing, used for navigating within the website.
// The baseUrl will be automatically prepended to this value.
to: 'docs/introduction',
// A full-page navigation, used for navigating outside of the website.
// You should only use either `to` or `href`.
href: 'https://www.facebook.com',
// Prepends the baseUrl to href values.
prependBaseUrlToHref: true,
// The string to be shown.
label: 'Introduction',
// Left or right side of the navbar.
position: 'left', // or 'right'
// To apply the active class styling on all
// routes starting with this path.
// This usually isn't necessary
activeBasePath: 'docs',
// Alternative to activeBasePath if required.
activeBaseRegex: 'docs/(next|v8)',
// Custom CSS class (for styling any item).
className: '',
},
// ... other links
],
},
// ...
},
};
```
React Router should automatically apply active link styling to links, but you can use `activeBasePath` in edge cases. For cases in which a link should be active on several different paths (such as when you have multiple doc folders under the same sidebar), you can use `activeBaseRegex`. `activeBaseRegex` is a more flexible alternative to `activeBasePath` and takes precedence over it -- Docusaurus parses it into a regular expression that is tested against the current URL.
Outbound (external) links automatically get `target="_blank" rel="noopener noreferrer"` attributes.
## Footer
You can add logo and a copyright to the footer via `themeConfig.footer`. Logo can be placed in [static folder](static-assets.md). Logo URL works in the same way of the navbar logo.
```js {5-15} title="docusaurus.config.js"
// ...
footer: {
logo: {
alt: 'Facebook Open Source Logo',
src: 'img/oss_logo.png',
href: 'https://opensource.facebook.com',
},
copyright: `Copyright © ${new Date().getFullYear()} My Project, Inc. Built with Docusaurus.`,
}
```
## Footer Links
You can add links to the navbar via `themeConfig.footer.links`:
```js {5-15} title="docusaurus.config.js"
module.exports = {
// ...
footer: {
links: [
{
// Label of the section of these links
title: 'Docs',
items: [
{
// Label of the link
label: 'Style Guide',
// Client-side routing, used for navigating within the website.
// The baseUrl will be automatically prepended to this value.
to: 'docs/',
},
{
label: 'Second Doc',
to: 'docs/doc2/',
},
],
},
{
title: 'Community',
items: [
{
label: 'Stack Overflow',
// A full-page navigation, used for navigating outside of the website.
href: 'https://stackoverflow.com/questions/tagged/docusaurus',
},
{
label: 'Discord',
href: 'https://discordapp.com/invite/docusaurus',
},
{
label: 'Twitter',
href: 'https://twitter.com/docusaurus',
},
{
//Renders the html pass-through instead of a simple link
html: `
<a href="https://www.netlify.com" target="_blank" rel="noreferrer noopener" aria-label="Deploys by Netlify">
<img src="https://www.netlify.com/img/global/badges/netlify-color-accent.svg" alt="Deploys by Netlify" />
</a>
`,
},
],
},
],
},
};
```

View file

@ -0,0 +1,355 @@
---
id: theme-classic
title: '@docusaurus/theme-classic'
---
:::caution
This section is a work in progress.
:::
## Common
### Color mode - dark mode
The classic theme provides by default light and dark mode support, with a navbar switch for the user.
It is possible to customize the color mode support with the following configuration:
```js {6-35} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
// ...
colorMode: {
// "light" | "dark"
defaultMode: 'light',
// Hides the switch in the navbar
// Useful if you want to support a single color mode
disableSwitch: false,
// Should we use the prefers-color-scheme media-query,
// using user system preferences, instead of the hardcoded defaultMode
respectPrefersColorScheme: false,
// Dark/light switch icon options
switchConfig: {
// Icon for the switch while in dark mode
darkIcon: '🌙',
// CSS to apply to dark icon,
// React inline style object
// see https://reactjs.org/docs/dom-elements.html#style
darkIconStyle: {
marginLeft: '2px',
},
// Unicode icons such as '\u2600' will work
// Unicode with 5 chars require brackets: '\u{1F602}'
lightIcon: '\u{1F602}'
lightIconStyle: {
marginLeft: '1px',
},
},
},
// ...
},
// ...
};
```
:::caution
With `respectPrefersColorScheme: true`, the `defaultMode` is overridden by user system preferences.
If you only want to support one color mode, you likely want to ignore user system preferences.
:::
### Meta image
You can configure a default image that will be used for your meta tag, in particular `og:image` and `twitter:image`.
```js {4-6} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
// Relative to your site's "static" directory.
// Cannot be SVGs. Can be external URLs too.
image: 'img/docusaurus.png',
// ...
},
};
```
### Announcement bar
Sometimes you want to announce something in your website. Just for such a case, you can add an announcement bar. This is a non-fixed and dismissable panel above the navbar.
```js {4-10} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
announcementBar: {
id: 'support_us', // Any value that will identify this message.
content:
'We are looking to revamp our docs, please fill <a target="_blank" rel="noopener noreferrer" href="#">this survey</a>',
backgroundColor: '#fafbfc', // Defaults to `#fff`.
textColor: '#091E42', // Defaults to `#000`.
},
// ...
},
};
```
## Hooks
### `useThemeContext`
React hook to access theme context. This context contains functions for setting light and dark mode and boolean property, indicating which mode is currently in use.
Usage example:
```jsx
import React from 'react';
// highlight-next-line
import useThemeContext from '@theme/hooks/useThemeContext';
const Example = () => {
// highlight-next-line
const {isDarkTheme, setLightTheme, setDarkTheme} = useThemeContext();
return <h1>Dark mode is now {isDarkTheme ? 'on' : 'off'}</h1>;
};
```
:::note
The component calling `useThemeContext` must be a child of the `Layout` component.
```jsx
function ExamplePage() {
return (
<Layout>
<Example />
</Layout>
);
}
```
:::
## Navbar
### Navbar title & logo
You can add a logo and title to the navbar via `themeConfig.navbar`. Logo can be placed in [static folder](static-assets.md). Logo URL is set to base URL of your site by default. Although you can specify your own URL for the logo, if it is an external link, it will open in a new tab. In addition, you can override a value for the target attribute of logo link, it can come in handy if you are hosting docs website in a subdirectory of your main website, and in which case you probably do not need a link in the logo to the main website will open in a new tab.
To improve dark mode support, you can also set a different logo for this mode.
```js {5-11} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
title: 'Site Title',
logo: {
alt: 'Site Logo',
src: 'img/logo.svg',
srcDark: 'img/logo_dark.svg', // Default to `logo.src`.
href: 'https://v2.docusaurus.io/', // Default to `siteConfig.baseUrl`.
target: '_self', // By default, this value is calculated based on the `href` attribute (the external link will open in a new tab, all others in the current one).
},
},
// ...
},
};
```
### Navbar items
You can add items to the navbar via `themeConfig.navbar.items`.
By default, Navbar items are regular links (internal or external).
```js {5-15} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
items: [
{
// Client-side routing, used for navigating within the website.
// The baseUrl will be automatically prepended to this value.
to: 'docs/introduction',
// A full-page navigation, used for navigating outside of the website.
// You should only use either `to` or `href`.
href: 'https://www.facebook.com',
// Prepends the baseUrl to href values.
prependBaseUrlToHref: true,
// The string to be shown.
label: 'Introduction',
// Left or right side of the navbar.
position: 'left', // or 'right'
// To apply the active class styling on all
// routes starting with this path.
// This usually isn't necessary
activeBasePath: 'docs',
// Alternative to activeBasePath if required.
activeBaseRegex: 'docs/(next|v8)',
// Custom CSS class (for styling any item).
className: '',
},
// ... other items
],
},
// ...
},
};
```
React Router should automatically apply active link styling to links, but you can use `activeBasePath` in edge cases. For cases in which a link should be active on several different paths (such as when you have multiple doc folders under the same sidebar), you can use `activeBaseRegex`. `activeBaseRegex` is a more flexible alternative to `activeBasePath` and takes precedence over it -- Docusaurus parses it into a regular expression that is tested against the current URL.
Outbound (external) links automatically get `target="_blank" rel="noopener noreferrer"` attributes.
### Navbar dropdown
Navbar items can also be dropdown items by specifying the `items`, an inner array of navbar items.
```js {9-19} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
items: [
{
label: 'Community',
position: 'left', // or 'right'
items: [
{
label: 'Facebook',
href: '...',
},
{
label: 'GitHub',
href: '...',
},
// ... more items
],
},
],
},
// ...
},
};
```
### Navbar docs version dropdown
If you use docs with versioning, this special navbar item type that will render a dropdown with all your site's available versions. The user will be able to switch from one version to another, while staying on the same doc (as long as the doc id is constant across versions).
```js {5-8} title="docusaurus.config.js"
module.exports = {
themeConfig: {
navbar: {
items: [
{
type: 'docsVersionDropdown',
position: 'left',
},
],
},
},
};
```
### Navbar docs version
If you use docs with versioning, this special navbar item type will link to the active/browsed version of your doc (depends on the current url), and fallback to the latest version.
```js {5-10} title="docusaurus.config.js"
module.exports = {
themeConfig: {
navbar: {
items: [
{
type: 'docsVersion',
position: 'left',
// to: "/path // by default, link to active/latest version
// label: "label" // by default, show active/latest version label
},
],
},
},
};
```
### Auto-hide sticky navbar
You can enable this cool UI feature that automatically hides the navbar when a user starts scrolling down the page, and show it again when the user scrolls up.
```js {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
navbar: {
hideOnScroll: true,
},
// ...
},
};
```
<!--
## Footer
TODO.
-->
## CodeBlock
Docusaurus uses [Prism React Renderer](https://github.com/FormidableLabs/prism-react-renderer) to highlight code blocks.
### Theme
By default, we use [Palenight](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/themes/palenight.js) as syntax highlighting theme. You can specify a custom theme from the [list of available themes](https://github.com/FormidableLabs/prism-react-renderer/tree/master/src/themes). If you want to use a different syntax highlighting theme when the site is in dark mode, you may also do so.
```js {5-6} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
prism: {
theme: require('prism-react-renderer/themes/github'),
darkTheme: require('prism-react-renderer/themes/dracula'),
},
// ...
},
};
```
:::note
If you use the line highlighting Markdown syntax, you might need to specify a different highlight background color for the dark mode syntax highlighting theme. Refer to the [docs for guidance](markdown-features.mdx#line-highlighting).
:::
### Default language
You can set a default language for code blocks if no language is added after the opening triple backticks (i.e. ```). Note that a valid [language name](https://prismjs.com/#supported-languages) must be passed, e.g.:
```js {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
prism: {
defaultLanguage: 'javascript',
},
// ...
},
};
```

View file

@ -0,0 +1,35 @@
---
id: typescript-support
title: TypeScript Support
---
## Setup
Docusaurus supports writing and using TypeScript theme components. To start using TypeScript, add `@docusaurus/module-type-aliases` and some `@types` dependencies to your project:
```bash
npm install --save-dev typescript @docusaurus/module-type-aliases @types/react @types/react-router-dom @types/react-helmet @tsconfig/docusaurus
```
Then add `tsconfig.json` to your project root with the following content:
```json title="tsconfig.json"
{
"extends": "@tsconfig/docusaurus/tsconfig.json",
"include": ["src/"]
}
```
Docusaurus doesn't use this `tsconfig.json` to compile your project. It is added just for a nicer Editor experience, although you can choose to run `tsc` to type check your code for yourself or on CI.
Now you can start writing TypeScript theme components.
## Swizzling TypeScript theme components
For themes that supports TypeScript theme components, you can add the `--typescript` flag to the end of swizzling command to get TypeScript source code. For example, the following command will generate `index.tsx` and `styles.module.css` into `src/theme/Footer`.
```bash npm2yarn
npm run swizzle @docusaurus/theme-classic Footer --typescript
```
At this moment, the only official Docusaurus theme that supports TypeScript theme components is `@docusaurus/theme-classic`. If you are a Docusaurus theme package author who wants to add TypeScript support, see the [Lifecycle APIs docs](./lifecycle-apis.md#gettypescriptthemepath).

View file

@ -0,0 +1,963 @@
---
id: using-plugins
title: Plugins
---
Plugins are the building blocks of features in a Docusaurus 2 site. Each plugin handles its own individual feature. Plugins may work and be distributed as part of bundle via [presets](presets.md).
## Installing a plugin
A plugin is usually a npm package, so you install them like other npm packages using npm.
```bash npm2yarn
npm install --save docusaurus-plugin-name
```
Then you add it in your site's `docusaurus.config.js`'s `plugins` option:
```jsx {3} title="docusaurus.config.js"
module.exports = {
// ...
plugins: ['@docusaurus/plugin-content-pages'],
};
```
Docusaurus can also load plugins from your local directory, you can do something like the following:
```jsx {5} title="docusaurus.config.js"
const path = require('path');
module.exports = {
// ...
plugins: [path.resolve(__dirname, '/path/to/docusaurus-local-plugin')],
};
```
## Configuring plugins
For the most basic usage of plugins, you can provide just the plugin name or the absolute path to the plugin.
However, plugins can have options specified by wrapping the name and an options object in an array inside your config. This style is usually called `Babel Style`.
```js {4-9} title="docusaurus.config.js"
module.exports = {
// ...
plugins: [
[
'@docusaurus/plugin-xxx',
{
/* options */
},
],
],
};
```
Example:
```js title="docusaurus.config.js"
module.exports = {
plugins: [
// Basic usage.
'@docusaurus/plugin-google-analytics',
// With options object (babel style)
[
'@docusaurus/plugin-sitemap',
{
cacheTime: 600 * 1000,
},
],
],
};
```
## Multi-instance plugins and plugin ids
It is possible to use multiple times the same plugin, on the same Docusaurus website.
In this case, you it is required to assign a unique id to each plugin instance.
By default, the plugin id is `default`.
```js {6,13} title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-xxx',
{
id: 'plugin-xxx-1',
// other options
},
],
[
'@docusaurus/plugin-xxx',
{
id: 'plugin-xxx-2',
// other options
},
],
],
};
```
## 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).
For example if you have a reference to a local folder such as this in your `docusaurus.config.js`:
```js title="docusaurus.config.js"
module.exports = {
// ...
plugins: [path.resolve(__dirname, 'my-plugin')],
};
```
Then in the folder `my-plugin` you can create an index.js such as this
```js title="index.js"
module.exports = function (context, options) {
// ...
return {
name: 'my-docusaurus-plugin',
async loadContent() {
/* ... */
},
async contentLoaded({content, actions}) {
/* ... */
},
/* other lifecycle API */
};
};
```
The `my-plugin` folder could also be a fully fledged package with it's own package.json and a `src/index.js` file for example
#### `context`
`context` is plugin-agnostic and the same object will be passed into all plugins used for a Docusaurus website. The `context` object contains the following fields:
```ts
interface LoadContext {
siteDir: string;
generatedFilesDir: string;
siteConfig: DocusaurusConfig;
outDir: string;
baseUrl: string;
}
```
#### `options`
`options` are the [second optional parameter when the plugins are used](using-plugins.md#configuring-plugins). `options` are plugin-specific and are specified by users when they use them in `docusaurus.config.js`. Alternatively, if preset contains the plugin, the preset will then be in charge of passing the correct options into the plugin. It is up to individual plugin to define what options it takes.
#### Return value
The returned object value should implement the [lifecycle APIs](lifecycle-apis.md).
## Official plugins
Find the list of official Docusaurus plugins [here](https://github.com/facebook/docusaurus/tree/master/packages).
### `@docusaurus/plugin-content-blog`
Provides the [Blog](blog.md) feature and is the default blog plugin for Docusaurus.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-content-blog
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. You can also configure it through the [classic preset options](presets.md#docusauruspreset-classic) instead of doing it like below.
:::
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-blog',
{
/**
* Path to data on filesystem relative to site dir.
*/
path: 'blog',
/**
* URL for editing a blog post.
* Example: 'https://github.com/facebook/docusaurus/edit/master/website/blog/'
*/
editUrl:
'https://github.com/facebook/docusaurus/edit/master/website/blog/',
/**
* Blog page meta description for better SEO
*/
blogDescription: 'Blog',
/**
* URL route for the blog section of your site.
* *DO NOT* include a trailing slash.
*/
routeBasePath: 'blog',
include: ['*.md', '*.mdx'],
postsPerPage: 10,
/**
* Theme components used by the blog pages.
*/
blogListComponent: '@theme/BlogListPage',
blogPostComponent: '@theme/BlogPostPage',
blogTagsListComponent: '@theme/BlogTagsListPage',
blogTagsPostsComponent: '@theme/BlogTagsPostsPage',
/**
* Remark and Rehype plugins passed to MDX.
*/
remarkPlugins: [
/* require('remark-math') */
],
rehypePlugins: [],
/**
* Custom Remark and Rehype plugins passed to MDX before
* the default Docusaurus Remark and Rehype plugins.
*/
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
/**
* Truncate marker, can be a regex or string.
*/
truncateMarker: /<!--\s*(truncate)\s*-->/,
/**
* Show estimated reading time for the blog post.
*/
showReadingTime: true,
/**
* Blog feed.
* If feedOptions is undefined, no rss feed will be generated.
*/
feedOptions: {
type: '', // required. 'rss' | 'feed' | 'all'
title: '', // default to siteConfig.title
description: '', // default to `${siteConfig.title} Blog`
copyright: '',
language: undefined, // possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
},
},
],
],
};
```
### `@docusaurus/plugin-content-docs`
Provides the [Docs](markdown-features.mdx) functionality and is the default docs plugin for Docusaurus.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-content-docs
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. You can also configure it through the [classic preset options](presets.md#docusauruspreset-classic) instead of doing it like below.
:::
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
/**
* Path to data on filesystem relative to site dir.
*/
path: 'docs',
/**
* URL for editing a doc in the website repo.
* Example: 'https://github.com/facebook/docusaurus/edit/master/website/'
*/
editUrl: 'https://github.com/facebook/docusaurus/edit/master/website/',
/**
* URL route for the docs section of your site.
* *DO NOT* include a 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: [
/* require('remark-math') */
],
rehypePlugins: [],
/**
* Custom Remark and Rehype plugins passed to MDX before
* the default Docusaurus Remark and Rehype plugins.
*/
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
/**
* Whether to display the author who last updated the doc.
*/
showLastUpdateAuthor: false,
/**
* Whether to display the last date the doc was updated.
*/
showLastUpdateTime: false,
/**
* By default, versioning is enabled on versioned sites.
* This is a way to explicitly disable the versioning feature.
*/
disableVersioning: false,
/**
* Skip the next release docs when versioning is enabled.
* This will not generate HTML files in the production build for documents
* in `/docs/next` directory, only versioned docs.
*/
excludeNextVersionDocs: false,
/**
* The last version is the one we navigate to in priority on versioned sites
* It is the one displayed by default in docs navbar items
* By default, the last version is the first one to appear in versions.json
* By default, the last version is at the "root" (docs have path=/docs/myDoc)
* Note: it is possible to configure the path and label of the last version
* Tip: using lastVersion: 'current' make sense in many cases
*/
lastVersion: undefined,
/**
* The docusaurus versioning defaults don't make sense for all projects
* This gives the ability customize the label and path of each version
* You may not like that default versin
*/
versions: {
/*
Example configuration:
current: {
label: 'Android SDK v2.0.0 (WIP)',
path: 'android-2.0.0',
},
'1.0.0': {
label: 'Android SDK v1.0.0',
path: 'android-1.0.0',
},
*/
},
},
],
],
};
```
### `@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](guides/creating-pages.md) functionality.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-content-pages
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. You can also configure it through the [classic preset options](presets.md#docusauruspreset-classic) instead of doing it like below.
:::
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/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 page section of your site
* do not include trailing slash
*/
routeBasePath: '',
include: ['**/*.{js,jsx,ts,tsx,md,mdx}'],
/**
* No Route will be created for matching files
*/
exclude: [
'**/_*.{js,jsx,ts,tsx,md,mdx}',
'**/*.test.{js,ts}',
'**/__tests__/**',
],
/**
* Theme component used by markdown pages.
*/
mdxPageComponent: '@theme/MDXPage',
/**
* Remark and Rehype plugins passed to MDX
*/
remarkPlugins: [],
rehypePlugins: [],
},
],
],
};
```
### `@docusaurus/plugin-google-analytics`
The default [Google Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/) plugin. It is a JavaScript library for measuring how users interact with your website.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-google-analytics
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency.
:::
**Configuration**
```js title="docusaurus.config.js"
module.exports = {
plugins: ['@docusaurus/plugin-google-analytics'],
themeConfig: {
googleAnalytics: {
trackingID: 'UA-141789564-1',
// Optional fields.
anonymizeIP: true, // Should IPs be anonymized?
},
},
};
```
### `@docusaurus/plugin-google-gtag`
The default [Global Site Tag (gtag.js)](https://developers.google.com/analytics/devguides/collection/gtagjs/) plugin. It is a JavaScript tagging framework and API that allows you to send event data to Google Analytics, Google Ads, and Google Marketing Platform. This section describes how to configure a Docusaurus site to enable global site tag for Google Analytics.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-google-gtag
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency.
:::
**Configuration**
```js title="docusaurus.config.js"
module.exports = {
plugins: ['@docusaurus/plugin-google-gtag'],
themeConfig: {
gtag: {
trackingID: 'UA-141789564-1',
// Optional fields.
anonymizeIP: true, // Should IPs be anonymized?
},
},
};
```
### `@docusaurus/plugin-sitemap`
This plugin creates sitemap for your site so that search engine crawlers can crawl your site more accurately.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-sitemap
```
:::tip
If you have installed `@docusaurus/preset-classic`, you don't need to install it as a dependency. You can also configure it through the [classic preset options](presets.md#docusauruspreset-classic) instead of doing it like below.
:::
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-sitemap',
{
cacheTime: 600 * 1000, // 600 sec - cache purge period
changefreq: 'weekly',
priority: 0.5,
},
],
],
};
```
### `@docusaurus/plugin-ideal-image`
Docusaurus Plugin to generate an almost ideal image (responsive, lazy-loading, and low quality placeholder) **in the production builds**.
```bash npm2yarn
npm install --save @docusaurus/plugin-ideal-image
```
Modify your `docusaurus.config.js`
```diff
module.exports = {
...
+ plugins: ['@docusaurus/plugin-ideal-image'],
...
}
```
#### Usage
This plugin supports the PNG, GIF and JPG formats only.
```jsx
import Image from '@theme/IdealImage';
import thumbnail from './path/to/img.png';
// your React code
<Image img={thumbnail} />
// or
<Image img={require('./path/to/img.png')} />
```
#### Options
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | `ideal-img/[name].[hash:hex:7].[width].[ext]` | Filename template for output files. |
| `sizes` | `array` | _original size_ | Specify all widths you want to use. If a specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up). |
| `size` | `integer` | _original size_ | Specify one width you want to use; if the specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up) |
| `min` | `integer` | | As an alternative to manually specifying `sizes`, you can specify `min`, `max` and `steps`, and the sizes will be generated for you. |
| `max` | `integer` | | See `min` above |
| `steps` | `integer` | `4` | Configure the number of images generated between `min` and `max` (inclusive) |
| `quality` | `integer` | `85` | JPEG compression quality |
### `@docusaurus/plugin-client-redirects`
Docusaurus Plugin to generate **client-side redirects**.
This plugin will write additional HTML pages to your static site, that redirects the user to your existing Docusaurus pages with JavaScript.
:::note
This plugin only create redirects for the production build.
:::
:::caution
It is better to use server-side redirects whenever possible.
Before using this plugin, you should look if your hosting provider doesn't offer this feature.
:::
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-client-redirects
```
**Configuration**
Main usecase: you have `/myDocusaurusPage`, and you want to redirect to this page from `/myDocusaurusPage.html`:
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
fromExtensions: ['html'],
},
],
],
};
```
Second usecase: you have `/myDocusaurusPage.html`, and you want to redirect to this page from `/myDocusaurusPage`.
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
toExtensions: ['html'],
},
],
],
};
```
For custom redirect logic, provide your own `createRedirects` function.
Let's imagine you change the url of an existing page, you might want to make sure the old url still works:
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
redirects: [
{
to: '/docs/newDocPath', // string
from: ['/docs/oldDocPathFrom2019', '/docs/legacyDocPathFrom2016'], // string | string[]
},
],
},
],
],
};
```
It's possible to use a function to create the redirects for each existing path:
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
createRedirects: function (existingPath) {
if (existingPath === '/docs/newDocPath') {
return ['/docs/oldDocPathFrom2019', '/docs/legacyDocPathFrom2016']; // string | string[]
}
},
},
],
],
};
```
Finally, it's possible to use all options at the same time:
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
fromExtensions: ['html', 'htm'],
toExtensions: ['exe', 'zip'],
redirects: [
{
to: '/docs/newDocPath',
from: '/docs/oldDocPath',
},
],
createRedirects: function (existingPath) {
if (existingPath === '/docs/newDocPath2') {
return ['/docs/oldDocPath2'];
}
},
},
],
],
};
```
### `@docusaurus/plugin-pwa`
Docusaurus Plugin to add PWA support using [Workbox](https://developers.google.com/web/tools/workbox). This plugin generates a [Service Worker](https://developers.google.com/web/fundamentals/primers/service-workers) in production build only, and allows you to create fully PWA-compliant documentation site with offline and installation support.
```bash npm2yarn
npm install --save @docusaurus/plugin-pwa
```
Create a [PWA manifest](https://web.dev/add-manifest/) at `./static/manifest.json`.
Modify `docusaurus.config.js` with a minimal PWA config, like:
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-pwa',
{
debug: true,
offlineModeActivationStrategies: ['appInstalled', 'queryString'],
pwaHead: [
{
tagName: 'link',
rel: 'icon',
href: '/img/docusaurus.png',
},
{
tagName: 'link',
rel: 'manifest',
href: '/manifest.json', // your PWA manifest
},
{
tagName: 'meta',
name: 'theme-color',
content: 'rgb(37, 194, 160)',
},
],
},
],
],
};
```
#### Progressive Web App
Having a service worker installed is not enough to make your application a PWA. You'll need to at least include a [Web App Manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest) and have the correct tags in `<head>` ([Options > pwaHead](#pwahead)).
After deployment, you can use [Lighthouse](https://developers.google.com/web/tools/lighthouse) to run an audit on your site.
For a more exhaustive list of what it takes for your site to be a PWA, refer to the [PWA Checklist](https://developers.google.com/web/progressive-web-apps/checklist)
#### App installation support
If your browser supports it, you should be able to install a Docusaurus site as an app.
![pwa_install.gif](/img/pwa_install.gif)
#### Offline mode (precaching)
We enable users to browse a Docusaurus site offline, by using service-worker precaching.
> ### [What is Precaching?](https://developers.google.com/web/tools/workbox/modules/workbox-precaching)
>
> One feature of service workers is the ability to save a set of files to the cache when the service worker is installing. This is often referred to as "precaching", since you are caching content ahead of the service worker being used.
>
> The main reason for doing this is that it gives developers control over the cache, meaning they can determine when and how long a file is cached as well as serve it to the browser without going to the network, meaning it can be used to create web apps that work offline.
>
> Workbox takes a lot of the heavy lifting out of precaching by simplifying the API and ensuring assets are downloaded efficiently.
By default, offline mode is enabled when the site is installed as an app. See the `offlineModeActivationStrategies` option for details.
After the site has been precached, the service worker will serve cached responses for later visits. When a new build is deployed along with a new service worker, the new one will begin installing and eventually move to a waiting state. During this waiting state, a reload popup will show and ask the user to reload the page for new content. Until the user either clears the application cache or clicks the `reload` button on the popup, the service worker will continue serving the old content.
:::caution
Offline mode / precaching requires downloading all the static assets of the site ahead of time, and can consume unnecessary bandwidth. It may not be a good idea to activate it for all kind of sites.
:::
##### Options
##### `debug`
- Type: `boolean`
- Default: `false`
Turn debug mode on:
- Workbox logs
- Additional Docusaurus logs
- Unoptimized SW file output
- Source maps
##### `offlineModeActivationStrategies`
- Type: `Array<'appInstalled' | 'mobile' | 'saveData'| 'queryString' | 'always'>`
- Default: `['appInstalled','queryString']`
Strategies used to turn the offline mode on:
- `appInstalled`: activates for users having installed the site as an app
- `queryString`: activates if queryString contains `offlineMode=true` (convenient for PWA debugging)
- `mobile`: activates for mobile users (width <= 940px)
- `saveData`: activates for users with `navigator.connection.saveData === true`
- `always`: activates for all users
:::caution
Use this carefully: some users may not like to be forced to use the offline mode.
:::
##### `injectManifestConfig`
[Workbox options](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.injectManifest) to pass to `workbox.injectManifest()`. This gives you control over which assets will be precached, and be available offline.
- Type: `InjectManifestOptions`
- Default: `{}`
```js title="docusaurus.config.js"
module.exports = {
plugins: [
[
'@docusaurus/plugin-pwa',
{
injectManifestConfig: {
manifestTransforms: [
//...
],
modifyURLPrefix: {
//...
},
// We already add regular static assets (html, images...) to be available offline
// You can add more files according to your needs
globPatterns: ['**/*.{pdf,docx,xlsx}'],
// ...
},
},
],
],
};
```
##### `reloadPopup`
- Type: `string | false`
- Default: `'@theme/PwaReloadPopup'`
Module path to reload popup component. This popup is rendered when a new service worker is waiting to be installed, and we suggest a reload to the user.
Passing `false` will disable the popup, but this is not recommended: users won't have a way to get up-to-date content.
A custom component can be used, as long as it accepts `onReload` as a prop. The `onReload` callback should be called when the `reload` button is clicked. This will tell the service worker to install the waiting service worker and reload the page.
```ts
interface PwaReloadPopupProps {
onReload: () => void;
}
```
The default theme includes an implementation for the reload popup and uses [Infima Alerts](https://facebookincubator.github.io/infima/docs/components/alert).
![pwa_reload.gif](/img/pwa_reload.gif)
##### `pwaHead`
- Type: `Array<{ tagName: string } & Record<string,string>>`
- Default: `[]`
Array of objects containing `tagName` and key-value pairs for attributes to inject into the `<head>` tag. Technically you can inject any head tag through this, but it's ideally used for tags to make your site PWA compliant. Here's a list of tag to make your app fully compliant:
```js
module.exports = {
plugins: [
[
'@docusaurus/plugin-pwa',
{
pwaHead: [
{
tagName: 'link',
rel: 'icon',
href: '/img/docusaurus.png',
},
{
tagName: 'link',
rel: 'manifest',
href: '/manifest.json',
},
{
tagName: 'meta',
name: 'theme-color',
content: 'rgb(37, 194, 160)',
},
{
tagName: 'meta',
name: 'apple-mobile-web-app-capable',
content: 'yes',
},
{
tagName: 'meta',
name: 'apple-mobile-web-app-status-bar-style',
content: '#000',
},
{
tagName: 'link',
rel: 'apple-touch-icon',
href: '/img/docusaurus.png',
},
{
tagName: 'link',
rel: 'mask-icon',
href: '/img/docusaurus.svg',
color: 'rgb(37, 194, 160)',
},
{
tagName: 'meta',
name: 'msapplication-TileImage',
content: '/img/docusaurus.png',
},
{
tagName: 'meta',
name: 'msapplication-TileColor',
content: '#000',
},
],
},
],
],
};
```
##### `swCustom`
- Type: `string | undefined`
- Default: `undefined`
Useful for additional Workbox rules. You can do whatever a service worker can do here, and use the full power of workbox libraries. The code is transpiled, so you can use modern ES6+ syntax here.
For example, to cache files from external routes:
```js
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
// default fn export receiving some useful params
export default function swCustom(params) {
const {
debug, // :boolean
offlineMode, // :boolean
} = params;
// Cache responses from external resources
registerRoute((context) => {
return [
/graph\.facebook\.com\/.*\/picture/,
/netlify\.com\/img/,
/avatars1\.githubusercontent/,
].some((regex) => context.url.href.match(regex));
}, new StaleWhileRevalidate());
}
```
The module should have a `default` function export, and receives some params.
##### `swRegister`
- Type: `string | false`
- Default: `'docusaurus-plugin-pwa/src/registerSW.js'`
Adds an entry before the Docusaurus app so that registration can happen before the app runs. The default `registerSW.js` file is enough for simple registration.
Passing `false` will disable registration entirely.

View file

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

View file

@ -0,0 +1,207 @@
---
id: versioning
title: Versioning
---
You can use the version script to create a new documentation version based on the latest content in the `docs` directory. That specific set of documentation will then be preserved and accessible even as the documentation in the `docs` directory changes moving forward.
:::caution
Think about it before starting to version your documentation - it can become difficult for contributors to help improve it!
:::
Most of the time, you don't need versioning as it will just increase your build time, and introduce complexity to your codebase. Versioning is **best suited for websites with high-traffic and rapid changes to documentation between versions**. If your documentation rarely changes, don't add versioning to your documentation.
To better understand how versioning works and see if it suits your needs, you can read on below.
## Directory structure
```shell
website
├── sidebars.json # sidebar for master (next) version
├── docs # docs directory for master (next) version
│ ├── foo
│ │ └── bar.md # https://mysite.com/docs/next/foo/bar
│ └── hello.md # https://mysite.com/docs/next/hello
├── versions.json # file to indicate what versions are available
├── versioned_docs
│ ├── version-1.1.0
│ │ ├── foo
│ │ │ └── bar.md # https://mysite.com/docs/foo/bar
│ │ └── hello.md
│ └── version-1.0.0
│ ├── foo
│ │ └── bar.md # https://mysite.com/docs/1.0.0/foo/bar
│ └── hello.md
├── versioned_sidebars
│ ├── version-1.1.0-sidebars.json
│ └── version-1.0.0-sidebars.json
├── docusaurus.config.js
└── package.json
```
The table below explains how a versioned file maps to its version and the generated URL.
| Path | Version | URL |
| --------------------------------------- | -------------- | ----------------- |
| `versioned_docs/version-1.0.0/hello.md` | 1.0.0 | /docs/1.0.0/hello |
| `versioned_docs/version-1.1.0/hello.md` | 1.1.0 (latest) | /docs/hello |
| `docs/hello.md` | next | /docs/next/hello |
### Tagging a new version
1. First, make sure your content in the `docs` directory is ready to be frozen as a version. A version always should be based from master.
1. Enter a new version number.
```bash npm2yarn
npm run docusaurus docs:version 1.1.0
```
When tagging a new version, the document versioning mechanism will:
- Copy the full `docs/` folder contents into a new `versioned_docs/version-<version>/` folder.
- Create a versioned sidebars file based from your current [sidebar](docs.md#sidebar) configuration (if it exists) - saved as `versioned_sidebars/version-<version>-sidebars.json`.
- Append the new version number to `versions.json`.
## Docs
### Creating new docs
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 docs
- 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
### Figure out the behavior for the "current" version
The "current" version is the version name for the `./docs` folder.
There are different ways to manage versioning, but two very common patterns are:
- You release v1, and start immediately working on v2 (including its docs)
- You release v1, and will maintain it for some time before thinking about v2.
Docusaurus defaults work great for the first usecase.
**For the 2nd usecase**: if you release v1 and don't plan to work on v2 anytime soon, instead of versioning v1 and having to maintain the docs in 2 folders (`./docs` + `./versioned_docs/version-1.0.0`), you may consider using the following configuration instead:
```json
{
"lastVersion": "current",
"versions": {
"current": {
"label": "1.0.0",
"path": "1.0.0"
}
}
}
```
The docs in `./docs` will be served at `/docs/1.0.0` instead of `/docs/next`, and `1.0.0` will become the default version we link to in the navbar dropdown, and you will only need to maintain a single `./docs` folder.
See [docs plugin configuration](using-plugins#docusaurusplugin-content-docs) for more details.
### 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';
```
### Global or versioned colocated assets
You should decide if assets like images and files are per version or shared between versions
If your assets should be versioned, put them in the docs version, and use relative paths:
```md
![img alt](./myImage.png)
[dowload this file](./file.pdf)
```
If your assets are global, put them in `/static` and use absolute paths:
```md
![img alt](/myImage.png)
[dowload this file](/file.pdf)
```

View file

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

View file

@ -1,4 +1,5 @@
[
"2.0.0-alpha.62",
"2.0.0-alpha.61",
"2.0.0-alpha.60",
"2.0.0-alpha.58",

View file

@ -17722,7 +17722,7 @@ react-dev-utils@^9.1.0:
strip-ansi "5.2.0"
text-table "0.2.0"
react-dom@^16.8.4:
react-dom@^16.10.2, react-dom@^16.8.4:
version "16.13.1"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-16.13.1.tgz#c1bd37331a0486c078ee54c4740720993b2e0e7f"
integrity sha512-81PIMmVLnCNLO/fFOQxdQkvEq/+Hfpv24XNJfpyZhTRfO0QcmQIF/PgCa1zCOj2w1hrn12MFLyaJ/G0+Mxtfag==
@ -17902,7 +17902,7 @@ react-waypoint@^9.0.2:
prop-types "^15.0.0"
react-is "^16.6.3"
react@^16.8.4:
react@^16.10.2, react@^16.8.4:
version "16.13.1"
resolved "https://registry.yarnpkg.com/react/-/react-16.13.1.tgz#2e818822f1a9743122c063d6410d85c1e3afe48e"
integrity sha512-YMZQQq32xHLX0bz5Mnibv1/LHb3Sqzngu7xstSM+vrkE5Kzr9xE0yMByK5kMoTK30YVJE61WfbxIFFvfeDKT1w==