diff --git a/website/versioned_docs/version-2.0.0-alpha.38/creating-pages.md b/website/versioned_docs/version-2.0.0-alpha.38/creating-pages.md deleted file mode 100644 index 0afcfdb9c5..0000000000 --- a/website/versioned_docs/version-2.0.0-alpha.38/creating-pages.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -id: creating-pages -title: Creating Pages ---- - -In this section, we will learn about creating ad-hoc pages in Docusaurus using React. This is most useful for creating one-off standalone pages like a showcase page, playground page or support page. - -## Adding a new page - - - -In the `/src/pages/` directory, create a file called `hello.js` with the following contents: - -```jsx -import React from 'react'; -import Layout from '@theme/Layout'; - -function Hello() { - return ( - -
-

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

-
-
- ); -} - -export default Hello; -``` - -Once you save the file, the development server will automatically reload the changes. Now open http://localhost:3000/hello, you will see the new page you just created. - -Each page doesn't come with any styling. You will need to import the `Layout` component from `@theme/Layout` and wrap your contents within that component if you want the navbar and/or footer to appear. - -## Routing - -If you are familiar with other static site generators like Jekyll and Next, this routing approach will feel familiar to you. Any JavaScript file you create under `/src/pages/` directory will be automatically converted to a website page, following the `/src/pages/` directory hierarchy. For example: - -- `/src/pages/index.js` → `/` -- `/src/pages/test.js` → `/test` -- `/src/pages/foo/test.js` → `/foo/test` -- `/src/pages/foo/index.js` → `/foo` - -In this component-based development era, it is encouraged to co-locate your styling, markup and behavior together into components. Each page is a component, and if you need to customize your page design with your own styles, we recommend co-locating your styles with the page component in its own directory. For example, to create a "Support" page, you could do one of the following: - -- Add a `/src/pages/support.js` file -- Create a `/src/pages/support/` directory and a `/src/pages/support/index.js` file. - -The latter is preferred as it has the benefits of letting you put files related to the page within that directory. For e.g. a CSS module file (`styles.module.css`) with styles meant to only be used on the "Support" page. **Note:** this is merely a recommended directory structure and you will still need to manually import the CSS module file within your component module (`support/index.js`). - -```sh -my-website -├── src -│ └── pages -│ ├── styles.module.css -│ ├── index.js -│ └── support -│ ├── index.js -│ └── styles.module.css -. -``` - -## Using React - -React is used as the UI library to create pages. Every page component should export a React component and you can leverage on the expressiveness of React to build rich and interactive content. - - diff --git a/website/versioned_docs/version-2.0.0-alpha.38/installation.md b/website/versioned_docs/version-2.0.0-alpha.38/installation.md deleted file mode 100644 index a98051d0c7..0000000000 --- a/website/versioned_docs/version-2.0.0-alpha.38/installation.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -id: installation -title: Installation ---- - -Docusaurus is essentially a set of npm [packages](https://github.com/facebook/docusaurus/tree/master/packages) that can be installed over npm. - -## Requirements - -- [Node.js](https://nodejs.org/en/download/) version >= 8.10.0 or above (which can be checked by running `node -v`). You can use [nvm](https://github.com/nvm-sh/nvm) for managing multiple Node versions on a single machine installed -- [Yarn](https://yarnpkg.com/en/) version >= 1.5 (which can be checked by running `yarn version`). Yarn is a performant package manager for JavaScript and replaces the `npm` client. It is not strictly necessary but highly encouraged. - -## Scaffold project website - -The easiest way to install Docusaurus is to use the command line tool that helps you scaffold a skeleton Docusaurus website. You can run this command anywhere in a new empty repository or within an existing repository, it will create a new directory containing the scaffolded files. - -```bash -npx @docusaurus/init@next init [name] [template] -``` - -Example: - -```bash -npx @docusaurus/init@next init my-website classic -``` - -If you do not specify `name` or `template`, it will prompt you for them. We recommend the `classic` template so that you can get started quickly and it contains features found in Docusaurus 1. The `classic` template contains `@docusaurus/preset-classic` which includes standard documentation, a blog, custom pages, and a CSS framework (with dark mode support). You can get up and running extremely quickly with the classic template and customize things later on when you have gained more familiarity with Docusaurus. - -## Project structure - -Assuming you chose the classic template and named your site `my-website`, you will see the following files generated under a new directory `my-website/`: - -```sh -my-website -├── blog -│ ├── 2019-05-28-hola.md -│ ├── 2019-05-29-hello-world.md -│ └── 2020-05-30-welcome.md -├── docs -│ ├── doc1.md -│ ├── doc2.md -│ ├── doc3.md -│ └── mdx.md -├── package.json -├── src -│ ├── css -│ │ └── custom.css -│ └── pages -│ ├── styles.module.css -│ └── index.js -├── static -│ └── img -├── docusaurus.config.js -├── package.json -├── README.md -├── sidebars.js -└── yarn.lock -``` - -### Project structure rundown - -- `/blog/` - Contains the blog markdown files. You can delete the directory if you do not want/need a blog. More details can be found in the [blog guide](blog.md). -- `/docs/` - Contains the markdown files for the docs. Customize the order of the docs sidebar in `sidebars.js`. More details can be found in the [docs guide](markdown-features.mdx). -- `/src/` - Non-documentation files like pages or custom React components. You don't have to strictly put your non-documentation files in here but putting them under a centralized directory makes it easier to specify in case you need to do some sort of linting/processing - - `/src/pages` - Any files within this directory will be converted into a website page. More details can be found in the [pages guide](creating-pages.md). -- `/static/` - Static directory. Any contents inside here will be copied into the root of the final `build` directory. -- `/docusaurus.config.js` - A config file containing the site configuration. This is the equivalent of `siteConfig.js` in Docusaurus 1. -- `/package.json` - A Docusaurus website is a React app. You can install and use any npm packages you like in them. -- `/sidebar.js` - Used by the documentation to specify the order of documents in the sidebar. - -## Running the development server - -To preview your changes as you edit the files, you can run a local development server that will serve your website and it will reflect the latest changes. - -```bash npm2yarn -cd my-website -npm run start -``` - -By default, a browser window will open at http://localhost:3000. - -Congratulations! You have just created your first Docusaurus site! Browse around the site to see what's available. - -## Build - -Docusaurus is a modern static website generator so we need to build the website into a directory of static contents and put it on a web server so that it can be viewed. To build the website: - -```bash npm2yarn -npm run build -``` - -and contents will be generated within the `/build` directory, which can be copied to any static file hosting service like [GitHub pages](https://pages.github.com/), [Now](https://zeit.co/now) or [Netlify](https://www.netlify.com/). Check out the docs on [deployment](deployment.md) for more details. - -## Problems? - -Ask for help on [Stack Overflow](https://stackoverflow.com/questions/tagged/docusaurus), on our [GitHub repository](https://github.com/facebook/docusaurus) or [Twitter](https://twitter.com/docusaurus). diff --git a/website/versioned_docs/version-2.0.0-alpha.38/lifecycle-apis.md b/website/versioned_docs/version-2.0.0-alpha.38/lifecycle-apis.md deleted file mode 100644 index 73fb577fa0..0000000000 --- a/website/versioned_docs/version-2.0.0-alpha.38/lifecycle-apis.md +++ /dev/null @@ -1,426 +0,0 @@ ---- -id: lifecycle-apis -title: Lifecycle APIs ---- - -> :warning: _This section is a work in progress._ - -Lifecycle APIs are shared by Themes and Plugins. - -## `getPathsToWatch()` - -Specifies the paths to watch for plugins and themes. The paths are watched by the dev server so that the plugin lifecycles are reloaded when contents in the watched paths change. Note that the plugins and themes modules are initially called with `context` and `options` from Node, which you may use to find the necessary directory information about the site. - -Example: - -```js {6-8} -// docusaurus-plugin/src/index.js -const path = require('path'); -module.exports = function(context, options) { - return { - name: 'docusaurus-plugin', - getPathsToWatch() { - const contentPath = path.resolve(context.siteDir, options.path); - return [`${contentPath}/**/*.{ts,tsx}`); - }, - }; -}; -``` - -## `async loadContent()` - -Plugins should use this lifecycle to fetch from data sources (filesystem, remote API, headless CMS, etc) or doing some server processing. - -For example, this plugin below return a random integer between 1 to 10 as content; - -```js {6-7} -// docusaurus-plugin/src/index.js -const path = require('path'); -module.exports = function(context, options) { - return { - name: 'docusaurus-plugin', - async loadContent() { - return 1 + Math.floor(Math.random() * 10); - }, - }; -}; -``` - -## `async contentLoaded({content, actions})` - -Plugins should use the data loaded in `loadContent` and construct the pages/routes that consume the loaded data (optional). - -### `content` - -`contentLoaded` will be called _after_ `loadContent` is done, the return value of `loadContent()` will be passed to `contentLoaded` as `content`. - -### `actions` - -`actions` contain two functions: - -- `addRoute(config: RouteConfig): void` - -Create a route to add to the website. - -```typescript -interface RouteConfig { - path: string; - component: string; - modules?: RouteModule; - routes?: RouteConfig[]; - exact?: boolean; - priority?: number; -} -interface RouteModule { - [module: string]: Module | RouteModule | RouteModule[]; -} -type Module = - | { - path: string; - __import?: boolean; - query?: ParsedUrlQueryInput; - } - | string; -``` - -- `createData(name: string, data: any): Promise` - -A helper function to help you write some data (usually a string or JSON) to disk with in-built caching. It takes a file name relative to to your plugin's directory **(name)**, your data **(data)**, and will return a path to where the data is created. - -For example, this plugin below create a `/roll` page which display "You won xxxx" to user. - -```jsx -// website/src/components/roll.js -import React from 'react'; - -export default function(props) { - const {prizes} = props; - const index = Math.floor(Math.random() * 3); - return
You won ${prizes[index]}
; -} -``` - -```javascript {5-20} -// docusaurus-plugin/src/index.js -module.exports = function(context, options) { - return { - name: 'docusaurus-plugin', - async contentLoaded({content, actions}) { - const {createData, addRoute} = actions; - // create a data named 'prizes.json' - const prizes = JSON.stringify(['$1', 'a cybertruck', 'nothing']); - const prizesDataPath = await createData('prizes.json', prizes); - - // add '/roll' page using 'website/src/component/roll.js` as the component - // and providing 'prizes' as props - addRoute({ - path: '/roll', - component: '@site/src/components/roll.js', - modules: { - prizes: prizesDataPath - } - exact: true, - }); - }, - }; -}; -``` - -## `configureWebpack(config, isServer, utils)` - -Modifies the internal webpack config. If the return value is a JavaScript object, it will be merged into the final config using [`webpack-merge`](https://github.com/survivejs/webpack-merge). If it is a function, it will be called and receive `config` as the first argument and an `isServer` flag as the argument argument. - -### `config` - -`configureWebpack` is called with `config` generated according to client/server build. You may treat this as the base config to be merged with. - -### `isServer` - -`configureWebpack` will be called both in server build and in client build. The server build receives `true` and the client build receives `false` as `isServer`. - -### `utils` - -The initial call to `configureWebpack` also receives a util object consists of three functions: - -- `getStyleLoaders(isServer: boolean, cssOptions: {[key: string]: any}): Loader[]` -- `getCacheLoader(isServer: boolean, cacheOptions?: {}): Loader | null` -- `getBabelLoader(isServer: boolean, babelOptions?: {}): Loader` - -You may use them to return your webpack configures conditionally. - -For example, this plugin below modify the webpack config to transpile `.foo` file. - -```js {5-12} -// docusaurus-plugin/src/index.js -module.exports = function(context, options) { - return { - name: 'docusaurus-plugin', - configureWebpack(config, isServer, utils) { - const {getCacheLoader} = utils; - config.module.rules.push({ - test: /\.foo$/, - use: [getCacheLoader(isServer), 'my-custom-webpack-loader'], - }); - return config; - }, - }; -}; -``` - -## 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[]; -}; -``` - -Example: - -```js {5-10} -// docusaurus-plugin/src/index.js -module.exports = function(context, options) { - return { - name: 'docusaurus-plugin', - async postBuild({siteConfig = {}, routesPaths = [], outDir}) { - // Print out to console all the rendered routes - routesPaths.map(route => { - console.log(route); - }); - }, - }; -}; -``` - -## `extendCli(cli)` - -Register an extra command to enhance the CLI of docusaurus. `cli` is [commander](https://www.npmjs.com/package/commander) object. - -Example: - -```js {5-12} -// docusaurus-plugin/src/index.js -module.exports = function(context, options) { - return { - name: 'docusaurus-plugin', - extendCli(cli) { - cli - .command('roll') - .description('Roll a random number between 1 and 1000') - .action(() => { - console.log(Math.floor(Math.random() * 1000 + 1)); - }); - }, - }; -}; -``` - -## `injectHtmlTags()` - -Inject head and/or body html tags to Docusaurus generated html. - -```typescript -function injectHtmlTags(): { - headTags?: HtmlTags; - preBodyTags?: HtmlTags; - postBodyTags?: HtmlTags; -}; - -type HtmlTags = string | HtmlTagObject | (string | HtmlTagObject)[]; - -interface HtmlTagObject { - /** - * Attributes of the html tag - * E.g. `{'disabled': true, 'value': 'demo', 'rel': 'preconnect'}` - */ - attributes?: { - [attributeName: string]: string | boolean; - }; - /** - * The tag name e.g. `div`, `script`, `link`, `meta` - */ - tagName: string; - /** - * The inner HTML - */ - innerHTML?: string; -} -``` - -Example: - -```js {5-29} -// docusaurus-plugin/src/index.js -module.exports = function(context, options) { - return { - name: 'docusaurus-plugin', - injectHtmlTags() { - return { - headTags: [ - { - tagName: 'link', - attributes: { - rel: 'preconnect', - href: 'https://www.github.com', - }, - }, - ], - preBodyTags: [ - { - tagName: 'script', - attributes: { - charset: 'utf-8', - src: '/noflash.js', - }, - }, - ], - postBodyTags: [`
This is post body
`], - }; - }, - }; -}; -``` - -## `getThemePath()` - -Returns the path to the directory where the theme components can be found. When your users calls `swizzle`, `getThemePath` is called and its returned path is used to find your theme components. - -If you use the folder directory above, your `getThemePath` can be: - -```js {7-9} -// my-theme/src/index.js -const path = require('path'); - -module.exports = function(context, options) { - return { - name: 'name-of-my-theme', - getThemePath() { - return path.resolve(__dirname, './theme'); - }, - }; -}; -``` - -## `getClientModules()` - -Returns an array of paths to the modules that are to be imported in the client bundle. These modules are imported globally before React even renders the initial UI. - -As an example, to make your theme load a `customCss` object from `options` passed in by the user: - -```js {8-10} -// my-theme/src/index.js -const path = require('path'); - -module.exports = function(context, options) { - const {customCss} = options || {}; - return { - name: 'name-of-my-theme', - getClientModules() { - return [customCss]; - }, - }; -}; -``` - - - -## Example - -Here's a mind model for a presumptuous plugin implementation. - -```jsx -const DEFAULT_OPTIONS = { - // Some defaults. -}; - -// A JavaScript function that returns an object. -// `context` is provided by Docusaurus. Example: siteConfig can be accessed from context. -// `opts` is the user-defined options. -module.exports = function(context, opts) { - // Merge defaults with user-defined options. - const options = {...DEFAULT_OPTIONS, ...options}; - - return { - // A compulsory field used as the namespace for directories to cache - // the intermediate data for each plugin. - // If you're writing your own local plugin, you will want it to - // be unique in order not to potentially conflict with imported plugins. - // A good way will be to add your own project name within. - name: 'docusaurus-my-project-cool-plugin', - - async loadContent() { - // The loadContent hook is executed after siteConfig and env has been loaded - // You can return a JavaScript object that will be passed to contentLoaded hook - }, - - async contentLoaded({content, actions}) { - // contentLoaded hook is done after loadContent hook is done - // actions are set of functional API provided by Docusaurus. e.g: addRoute - }, - - async postBuild(props) { - // after docusaurus finish - }, - - // TODO - async postStart(props) { - // docusaurus finish - }, - - // TODO - afterDevServer(app, server) { - // https://webpack.js.org/configuration/dev-server/#devserverbefore - }, - - // TODO - beforeDevServer(app, server) { - // https://webpack.js.org/configuration/dev-server/#devserverafter - }, - - configureWebpack(config, isServer) { - // Modify internal webpack config. If returned value is an Object, it - // will be merged into the final config using webpack-merge; - // If the returned value is a function, it will receive the config as the 1st argument and an isServer flag as the 2nd argument. - }, - - getPathsToWatch() { - // Path to watch - }, - - getThemePath() { - // Returns the path to the directory where the theme components can - // be found. - }, - - getClientModules() { - // Return an array of paths to the modules that are to be imported - // in the client bundle. These modules are imported globally before - // React even renders the initial UI. - }, - - extendCli(cli) { - // Register an extra command to enhance the CLI of docusaurus - }, - - injectHtmlTags() { - // Inject head and/or body html tags - }, - }; -}; -``` diff --git a/website/versioned_docs/version-2.0.0-alpha.38/markdown-features.mdx b/website/versioned_docs/version-2.0.0-alpha.38/markdown-features.mdx deleted file mode 100644 index 34c62c0ff0..0000000000 --- a/website/versioned_docs/version-2.0.0-alpha.38/markdown-features.mdx +++ /dev/null @@ -1,464 +0,0 @@ ---- -id: markdown-features -title: Markdown Features -description: Docusaurus uses GitHub Flavored Markdown (GFM). Find out more about Docusaurus-specific features when writing Markdown. ---- - - - -Documentation is one of your product's interfaces with your users. A well-written and well-organized set of docs helps your users understand your product quickly. Our aligned goal here is to help your users find and understand the information they need, as quickly as possible. - -Docusaurus 2 uses modern tooling to help you compose your interactive documentations with ease. You may embed React components, or build live coding blocks where your users may play with the code on the spot. Start sharing your eureka moments with the code your audience cannot walk away from. It is perhaps the most effective way of attracting potential users. - -In this section, we'd like to introduce you to the tools we've picked that we believe will help you build powerful documentation. Let us walk you through with an example. - -**Note:** All the following content assumes you are using `docusaurus-preset-classic`. - ---- - -Markdown is a syntax that enables you to write formatted content in a readable syntax. The [standard Markdown syntax](https://daringfireball.net/projects/markdown/syntax) is supported and we use [MDX](https://mdxjs.com/) as the parsing engine, which can do much more than just parsing Markdown. More on that later. - -Create a markdown file, `greeting.md`, and place it under the `docs` directory. - -```bash -website # root directory of your site -├── docs -│   └── greeting.md -├── src -│   └── pages -├── docusaurus.config.js -├── ... -``` - - - -In the top of the file, specify `id` the `title` in the front matter, so that Docusaurus will pick them up correctly when generating your site. - -```yml ---- -id: greeting -title: Hello ---- - -## Hello from Docusaurus - -Are you ready to create the documentation site for your open source project? - -### Headers - -will show up on the table of contents on the upper right - -So that your users will know what this page is all about without scrolling down or even without reading too much. - -### Only h2 and h3 will be in the toc - -The headers are well-spaced so that the hierarchy is clear. - -- lists will help you -- present the key points -- that you want your users to remember - - and you may nest them - - multiple times -``` - -This will render in the browser as follows: - -import BrowserWindow from '@site/src/components/BrowserWindow'; - - -

Hello from Docusaurus

- -Are you ready to create the documentation site for your open source project? - -

Headers

- -will show up on the table of contents on the upper right - -So that your users will know what this page is all about without scrolling down or even without reading too much. - -

Only h2 and h3 will be in the toc

- -The headers are well-spaced so that the hierarchy is clear. - -- lists will help you -- present the key points -- that you want your users to remember - - and you may nest them - - multiple times - -
- -### Markdown Headers - -Documents use the following markdown header fields that are enclosed by a line `---` on either side: - -- `id`: A unique document id. If this field is not present, the document's `id` will default to its file name (without the extension). -- `title`: The title of your document. If this field is not present, the document's `title` will default to its `id`. -- `hide_title`: Whether to hide the title at the top of the doc. By default it is `false`. -- `hide_table_of_contents`: Whether to hide the table of contents to the right. By default it is `false`. -- `sidebar_label`: The text shown in the document sidebar and in the next/previous button for this document. If this field is not present, the document's `sidebar_label` will default to its `title`. -- `custom_edit_url`: The URL for editing this document. If this field is not present, the document's edit URL will fall back to `editUrl` from options fields passed to `docusaurus-plugin-content-docs`. -- `keywords`: Keywords meta tag for the document page, for search engines. -- `description`: The description of your document, which will become the `` and `` in ``, used by search engines. If this field is not present, it will default to the first line of the contents. -- `image`: Cover or thumbnail image that will be used when displaying the link to your post. - -Example: - -```yml ---- -id: doc-markdown -title: Markdown Features -hide_title: false -hide_table_of_contents: false -sidebar_label: Markdown :) -custom_edit_url: https://github.com/facebook/docusaurus/edit/master/docs/api-doc-markdown.md -description: How do I find you when I cannot solve this problem -keywords: - - docs - - docusaurus -image: https://i.imgur.com/mErPwqL.png ---- -``` - -### Embedding React components - -Docusaurus has built-in support for [MDX](https://mdxjs.com), which allows you to write JSX within your Markdown files and render them as React components. - -**Note 1:** While both `.md` and `.mdx` files are parsed using MDX, some of the syntax are treated slightly differently. For the most accurate parsing and better editor support, we recommend using the `.mdx` extension for files containing MDX syntax. Let's rename the previous file to `greeting.mdx`. - -**Note 2:** Since all doc files are parsed using MDX, any HTML is treated as JSX. Therefore, if you need to inline-style a component, follow JSX flavor and provide style objects. This behavior is different from Docusaurus 1. See also [Migrating from v1 to v2](./migrating-from-v1-to-v2.md#convert-style-attributes-to-style-objects-in-mdx). - -Try this block here: - -```jsx -export const Highlight = ({children, color}) => ( - - {children} - -); - -Docusaurus green and Facebook blue are my favorite colors. - -I can write **Markdown** alongside my _JSX_! -``` - -Notice how it renders both the markup from your React component and the Markdown syntax: - -export const Highlight = ({children, color}) => ( - - {children} - -); - - -Docusaurus green and Facebook blue are my favorite colors. - -I can write **Markdown** alongside my _JSX_! - - - -
- -You can also import your own components defined in other files or third-party components installed via npm! Check out the [MDX docs](https://mdxjs.com/) to see what other fancy stuff you can do with MDX. - -### Referencing other documents - -If you want to reference another document file, you should use the name of the document you want to reference. Docusaurus will convert the file path to be the final website path (and remove the `.md`). - -For example, if you are in `doc2.md` and you want to reference `doc1.md` and `folder/doc3.md`: - -```md -I am referencing a [document](doc1.md). Reference to another [document in a folder](folder/doc3.md) -[Relative document](../doc2.md) referencing works as well. -``` - -One benefit of this approach is that the links to external files will still work if you are viewing the file on GitHub. - -### Syntax highlighting - -Code blocks are text blocks wrapped around by strings of 3 backticks. You may check out [this reference](https://github.com/mdx-js/specification) for specifications of MDX. - - ```jsx - console.log('Every repo must come with a mascot.'); - ``` - - - -Use the matching language meta string for your code block, and Docusaurus will pick up syntax highlighting automatically, powered by [Prism React Renderer](https://github.com/FormidableLabs/prism-react-renderer). - -```jsx -console.log('Every repo must come with a mascot.'); -``` - -By default, the Prism [syntax highlighting theme](https://github.com/FormidableLabs/prism-react-renderer#theming) we use is [Palenight](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/themes/palenight.js). You can change this to another theme by passing `theme` field in `prism` as `themeConfig` in your docusaurus.config.js. - -For example, if you prefer to use the `dracula` highlighting theme: - -```js {4} -// docusaurus.config.js -module.exports = { - themeConfig: { - prism: { - theme: require('prism-react-renderer/themes/dracula'), - }, - }, -}; -``` - -By default, Docusaurus comes with this subset of [commonly used languages](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/vendor/prism/includeLangs.js). - -To add syntax highlighting for any of the other [Prism supported languages](https://prismjs.com/#supported-languages), install the `prismjs` npm package, then swizzle the `CodeBlock` component and add the desired language(s) there. - -For example, if you want to add highlighting for the `powershell` language: - -```js -// src/theme/CodeBlock/index.js -import Prism from 'prism-react-renderer/prism'; -(typeof global !== 'undefined' ? global : window).Prism = Prism; -require('prismjs/components/prism-powershell'); -``` - -### Line highlighting - -You can bring emphasis to certain lines of code by specifying line ranges after the language meta string (leave a space after the language). - - ```jsx {3} - function HighlightSomeText(highlight) { - if (highlight) { - return 'This text is highlighted!'; - } - - return 'Nothing highlighted'; - } - ``` - -```jsx {3} -function HighlightSomeText(highlight) { - if (highlight) { - return 'This text is highlighted!'; - } - - return 'Nothing highlighted'; -} -``` - -To accomplish this, Docusaurus adds the `docusaurus-highlight-code-line` class to the highlighted lines. You will need to define your own styling for this CSS, possibly in your `src/css/custom.css` with a custom background color which is dependent on your selected syntax highlighting theme. The color given below works for the default highlighting theme (Palenight), so if you are using another theme will have to tweak the color accordingly. - -```css -/* /src/css/custom.css */ -.docusaurus-highlight-code-line { - background-color: rgb(72, 77, 91); - display: block; - margin: 0 calc(-1 * var(--ifm-pre-padding)); - padding: 0 var(--ifm-pre-padding); -} -``` - -To highlight multiple lines, separate the line numbers by commas or use the range syntax to select a chunk of lines. This feature uses the `parse-number-range` library and you can find [more syntax](<(https://www.npmjs.com/package/parse-numeric-range)>) on their project details. - - ```jsx {1,4-6,11} - import React from 'react'; - - function MyComponent(props) { - if (props.isBar) { - return
Bar
; - } - - return
Foo
; - } - - export default MyComponent; - ``` - -```jsx {1,4-6,11} -import React from 'react'; - -function MyComponent(props) { - if (props.isBar) { - return
Bar
; - } - - return
Foo
; -} - -export default MyComponent; -``` - -### Interactive code editor - -(Powered by [React Live](https://github.com/FormidableLabs/react-live)) - -You can create an interactive coding editor with the `@docusaurus/theme-live-codeblock` plugin. - -First, add the plugin to your package. - -```bash npm2yarn -npm install --save @docusaurus/theme-live-codeblock -``` - -You will also need to add the plugin to your `docusaurus.config.js`. - -```js {3} -module.exports = { - ... - themes: ['@docusaurus/theme-live-codeblock'], - ... -} -``` - -To use the plugin, create a code block with `live` attached to the language meta string. - - ```jsx live - function Clock(props) { - const [date, setDate] = useState(new Date()); - useEffect(() => { - var timerID = setInterval(() => tick(), 1000); - - return function cleanup() { - clearInterval(timerID); - }; - }); - - function tick() { - setDate(new Date()); - } - - return ( -
-

It is {date.toLocaleTimeString()}.

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

It is {date.toLocaleTimeString()}.

-
- ); -} -``` - -### Multi-language support code blocks - -With MDX, you can easily create interactive components within your documentation, for example, to display code in multiple programming languages and switching between them using a tabs component. - -Instead of implementing a dedicated component for multi-language support code blocks, we've implemented a generic Tabs component in the classic theme so that you can use it for other non-code scenarios as well. - -The following example is how you can have multi-language code tabs in your docs. Note that the empty lines above and below each language block is **intentional**. This is a current limitation of MDX, you have to leave empty lines around Markdown syntax for the MDX parser to know that it's Markdown syntax and not JSX. - - import Tabs from '@theme/Tabs'; - import TabItem from '@theme/TabItem'; - - - - - ```js - function helloWorld() { - console.log('Hello, world!'); - } - ``` - - - - - ```py - def hello_world(): - print 'Hello, world!' - ``` - - - - - ```java - class HelloWorld { - public static void main(String args[]) { - System.out.println("Hello, World"); - } - } - ``` - - - - -And you will get the following: - - - - -```js -function helloWorld() { - console.log('Hello, world!'); -} -``` - - - - -```py -def hello_world(): - print 'Hello, world!' -``` - - - - -```java -class HelloWorld { - public static void main(String args[]) { - System.out.println("Hello, World"); - } -} -``` - - - - -You may want to implement your own `` abstraction if you find the above approach too verbose. We might just implement one in future for convenience. diff --git a/website/versioned_docs/version-2.0.0-alpha.38/migrating-from-v1-to-v2.md b/website/versioned_docs/version-2.0.0-alpha.38/migrating-from-v1-to-v2.md deleted file mode 100644 index 53c9f771d8..0000000000 --- a/website/versioned_docs/version-2.0.0-alpha.38/migrating-from-v1-to-v2.md +++ /dev/null @@ -1,684 +0,0 @@ ---- -id: migrating-from-v1-to-v2 -title: Migrating from v1 to v2 ---- - -This doc guides you through migrating an existing Docusaurus 1 site to Docusaurus 2. - -**Note: This migration guide is targeted at Docusaurus users without translation and/or versioning features and assumes the following structure:** - -```sh -├── docs -└── website - ├── blog - ├── core - │ └── Footer.js - ├── package.json - ├── pages - ├── sidebars.json - ├── siteConfig.js - └── static -``` - -## Project setup - -### `package.json` - -#### Scoped package names - -In Docusaurus 2, we use scoped package names: - -- `docusaurus` -> `@docusaurus/core` - -This provides a clear distinction between Docusaurus' official packages and community maintained packages. In another words, all Docusaurus' official packages are namespaced under `@docusaurus/`. - -Meanwhile, the default doc site functionalities provided by Docusaurus 1 are now provided by `@docusaurus/preset-classic`. Therefore, we need to add this dependency as well: - -```json -// package.json -{ - dependencies: { -- "docusaurus": "^1.x.x", -+ "@docusaurus/core": "^2.0.0-alpha.38", -+ "@docusaurus/preset-classic": "^2.0.0-alpha.38", - } -} -``` - -#### CLI commands - -Meanwhile, CLI commands are renamed to `docusaurus ` (instead of `docusaurus-command`). - -The `"scripts"` section of your `package.json` should be updated as follows: - -```json {3-6} -{ - "scripts": { - "start": "docusaurus start", - "build": "docusaurus build", - "swizzle": "docusaurus swizzle", - "deploy": "docusaurus deploy" - ... - } -} -``` - -A typical Docusaurus 2 `package.json` may look like this: - -```json -{ - "scripts": { - "start": "docusaurus start", - "build": "docusaurus build", - "swizzle": "docusaurus swizzle", - "deploy": "docusaurus deploy" - }, - "dependencies": { - "@docusaurus/core": "^2.0.0-alpha.38", - "@docusaurus/preset-classic": "^2.0.0-alpha.38", - "classnames": "^2.2.6", - "react": "^16.10.2", - "react-dom": "^16.10.2" - }, - "browserslist": { - "production": [">0.2%", "not dead", "not op_mini all"], - "development": [ - "last 1 chrome version", - "last 1 firefox version", - "last 1 safari version" - ] - } -} -``` - -### Update references to the `build` directory - -In Docusaurus 1, all the build artifacts are located within `website/build/`. However, in Docusaurus 2, it is now moved to just `website/build`. Make sure that you update your deployment configuration to read the generated files from the correct `build` directory. - -If you are deploying to GitHub pages, make sure to run `yarn deploy` instead of `yarn publish-gh-pages` script. - -### `.gitignore` - -The `.gitignore` in your `website` should contain: - -``` -# dependencies -/node_modules - -# production -/build - -# generated files -.docusaurus -.cache-loader - -# misc -.DS_Store -.env.local -.env.development.local -.env.test.local -.env.production.local - -npm-debug.log* -yarn-debug.log* -yarn-error.log* -``` - -## Site configurations - -### `docusaurus.config.js` - -Rename `siteConfig.js` to `docusaurus.config.js`. In Docusaurus 2, we split each functionality (blog, docs, pages) into plugins for modularity. Presets are bundles of plugins and for backward compatibility we built a `@docusaurus/preset-classic` preset which bundles most of the essential plugins present in Docusaurus 1. - -Add the following preset configuration to your `docusaurus.config.js`. - -```jsx -// docusaurus.config.js -module.exports = { - // ... - presets: [ - [ - '@docusaurus/preset-classic', - { - docs: { - // docs folder path relative to website dir. - path: '../docs', - // sidebars file relative to website dir. - sidebarPath: require.resolve('./sidebars.json'), - }, - ... - }, - ], - ], -}; -``` - -Refer to migration guide below for each field in `siteConfig.js`. - -### Updated fields - -#### `baseUrl`, `tagline`, `title`, `url`, `favicon`, `organizationName`, `projectName`, `githubHost`, `scripts`, `stylesheets` - -No actions needed. - -#### `colors` - -Deprecated. We wrote a custom CSS framework for Docusaurus 2 called Infima which uses CSS variables for theming. The docs are not quite ready yet and we will update here when it is. To overwrite Infima' CSS variables, create your own CSS file (e.g. `./src/css/custom.css`) and import it globally by passing it as an option to `@docusaurus/preset-classic`: - -```js {8-10} -// docusaurus.config.js -module.exports = { - // ... - presets: [ - [ - '@docusaurus/preset-classic', - { - theme: { - customCss: require.resolve('./src/css/custom.css'), - }, - }, - ], - ], -}; -``` - -Infima uses 7 shades of each color. We recommend using [ColorBox](https://www.colorbox.io/) to find the different shades of colors for your chosen primary color. - -```css -/** - * /src/css/custom.css - * You can override the default Infima variables here. - * Note: this is not a complete list of --ifm- variables. - */ -:root { - --ifm-color-primary: #25c2a0; - --ifm-color-primary-dark: rgb(33, 175, 144); - --ifm-color-primary-darker: rgb(31, 165, 136); - --ifm-color-primary-darkest: rgb(26, 136, 112); - --ifm-color-primary-light: rgb(70, 203, 174); - --ifm-color-primary-lighter: rgb(102, 212, 189); - --ifm-color-primary-lightest: rgb(146, 224, 208); -} -``` - -#### `footerIcon`, `copyright`, `ogImage`, `twitterImage`, `docsSideNavCollapsible` - -Site meta info such as assets, SEO, copyright info are now handled by themes. To customize them, use the `themeConfig` field in your `docusaurus.config.js`: - -```jsx -// docusaurus.config.js -module.exports = { - // ... - themeConfig: { - footer: { - logo: { - alt: 'Facebook Open Source Logo', - src: 'https://docusaurus.io/img/oss_logo.png', - href: 'https://opensource.facebook.com/', - }, - copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`, - }, - image: 'img/docusaurus.png', - // Equivalent to `docsSideNavCollapsible` - sidebarCollapsible: false, - // ... - }, -}; -``` - -#### `headerIcon`, `headerLinks` - -In Docusaurus 1, header icon and header links were root fields in `siteConfig`: - -```js -headerIcon: 'img/docusaurus.svg', -headerLinks: [ - { doc: "doc1", label: "Getting Started" }, - { page: "help", label: "Help" }, - { href: "https://github.com/", label: "GitHub" }, - { blog: true, label: "Blog" }, -], -``` - -Now, these two fields are both handled by the theme: - -```jsx {7-20} -// docusaurus.config.js -module.exports = { - // ... - themeConfig: { - navbar: { - title: 'Docusaurus', - logo: { - alt: 'Docusaurus Logo', - src: 'img/docusaurus.svg', - }, - links: [ - {to: 'docs/doc1', label: 'Getting Started', position: 'left'}, - {to: 'help', label: 'Help', position: 'left'}, - { - href: 'https://github.com/', - label: 'GitHub', - position: 'right', - }, - {to: 'blog', label: 'Blog', position: 'left'}, - ], - }, - // ... - }, -}; -``` - -#### `algolia` - -```jsx {5-9} -// docusaurus.config.js -module.exports = { - // ... - themeConfig: { - algolia: { - apiKey: '47ecd3b21be71c5822571b9f59e52544', - indexName: 'docusaurus-2', - algoliaOptions: { ... }, - }, - // ... - }, -}; -``` - -#### `blogSidebarCount` - -Deprecated. Pass it as a blog option to `@docusaurus/preset-classic` instead: - -```jsx {9} -// docusaurus.config.js -module.exports = { - // ... - presets: [ - [ - '@docusaurus/preset-classic', - { - blog: { - postsPerPage: 10, - }, - // ... - }, - ], - ], -}; -``` - -#### `cname` - -Deprecated. Create a `CNAME` file in your `static` folder instead with your custom domain. Files in the `static` folder will be copied into the root of the `build` folder during execution of the build command. - -#### `customDocsPath`, `docsUrl`, `editUrl`, `enableUpdateBy`, `enableUpdateTime` - -**BREAKING**: `editUrl` should point to (website) docusaurus project instead of `docs` directory. - -Deprecated. Pass it as an option to `@docusaurus/preset-classic` docs instead: - -```jsx {9-22} -// docusaurus.config.js -module.exports = { - // ... - presets: [ - [ - '@docusaurus/preset-classic', - { - docs: { - // Equivalent to `customDocsPath`. - path: 'docs', - // Equivalent to `editUrl` but should point to `website` dir instead of `website/docs` - editUrl: 'https://github.com/facebook/docusaurus/edit/master/website', - // Equivalent to `docsUrl`. - routeBasePath: 'docs', - // Remark and Rehype plugins passed to MDX. Replaces `markdownOptions` and `markdownPlugins`. - remarkPlugins: [], - rehypePlugins: [], - // Equivalent to `enableUpdateBy`. - showLastUpdateAuthor: true, - // Equivalent to `enableUpdateTime`. - showLastUpdateTime: true, - }, - // ... - }, - ], - ], -}; -``` - -#### `gaTrackingId` - -```jsx {6} -// docusaurus.config.js -module.exports = { - // ... - themeConfig: { - googleAnalytics: { - trackingID: 'UA-141789564-1', - }, - // ... - }, -}; -``` - -#### `gaGtag` - -```jsx {6} -// docusaurus.config.js -module.exports = { - // ... - themeConfig: { - gtag: { - trackingID: 'UA-141789564-1', - }, - // ... - }, -}; -``` - -### Removed fields - -The following fields are all deprecated, you may remove from your configuration file. - -- `blogSidebarTitle` -- `cleanUrl` - Clean URL is used by default now. -- `defaultVersionShown` - Versioning is not ported yet. You'd be unable to migration to Docusaurus 2 if you are using versioning. Stay tuned. -- `disableHeaderTitle` -- `disableTitleTagline` -- `docsSideNavCollapsible` is available at `themeConfig.sidebarCollapsible`, and this is turned on by default now. -- `facebookAppId` -- `facebookComments` -- `facebookPixelId` -- `fonts` -- `highlight` - We now use [Prism](https://prismjs.com/) instead of [highlight.js](https://highlightjs.org/). -- `markdownOptions` - We use MDX in v2 instead of Remarkable. Your markdown options have to be converted to Remark/Rehype plugins. -- `markdownPlugins` - We use MDX in v2 instead of Remarkable. Your markdown plugins have to be converted to Remark/Rehype plugins. -- `manifest` -- `noIndex` -- `onPageNav` - This is turned on by default now. -- `separateCss` - It can imported in the same manner as `custom.css` mentioned above. -- `scrollToTop` -- `scrollToTopOptions` -- `translationRecruitingLink` -- `twitter` -- `twitterUsername` -- `useEnglishUrl` -- `users` -- `usePrism` - We now use [Prism](https://prismjs.com/) instead of [highlight.js](https://highlightjs.org/) -- `wrapPagesHTML` - -We intend to implement many of the deprecated config fields as plugins in future. Help will be appreciated! - -## Components - -### Sidebar - -In previous version, nested sidebar category is not allowed and sidebar category can only contain doc id. However, v2 allows infinite nested sidebar and we have many types of [Sidebar Item](sidebar.md#sidebar-item) other than document. - -You'll have to migrate your sidebar if it contains category type. Rename `subcategory` to `category` and `ids` to `items`. - -```js -{ -- type: 'subcategory', -+ type: 'category', - label: 'My Example Subcategory', -+ items: ['doc1'], -- ids: ['doc1'] -}, -``` - -### Footer - -`website/core/Footer.js` is no longer needed. If you want to modify the default footer provided by docusaurus, [swizzle](using-themes.md#swizzling-theme-components) it: - -```bash npm2yarn -npm run swizzle @docusaurus/theme-classic Footer -``` - -This will copy the current `