docs: normalize CodeBlock highlighting (#6223)

This commit is contained in:
Joshua Chen 2021-12-30 10:51:00 +08:00 committed by GitHub
parent c45281a581
commit 4872decb42
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 159 additions and 86 deletions

View file

@ -14,15 +14,17 @@ Use this for files that are consumed server-side, because theme files are automa
Example: Example:
```js {5-7} title="docusaurus-plugin/src/index.js" ```js title="docusaurus-plugin/src/index.js"
const path = require('path'); const path = require('path');
module.exports = function (context, options) { module.exports = function (context, options) {
return { return {
name: 'docusaurus-plugin', name: 'docusaurus-plugin',
// highlight-start
getPathsToWatch() { getPathsToWatch() {
const contentPath = path.resolve(context.siteDir, options.path); const contentPath = path.resolve(context.siteDir, options.path);
return [`${contentPath}/**/*.{ts,tsx}`]; return [`${contentPath}/**/*.{ts,tsx}`];
}, },
// highlight-end
}; };
}; };
``` ```
@ -39,10 +41,11 @@ The commander version matters! We use commander v5, and make sure you are referr
Example: Example:
```js {4-11} title="docusaurus-plugin/src/index.js" ```js title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) { module.exports = function (context, options) {
return { return {
name: 'docusaurus-plugin', name: 'docusaurus-plugin',
// highlight-start
extendCli(cli) { extendCli(cli) {
cli cli
.command('roll') .command('roll')
@ -51,6 +54,7 @@ module.exports = function (context, options) {
console.log(Math.floor(Math.random() * 1000 + 1)); console.log(Math.floor(Math.random() * 1000 + 1));
}); });
}, },
// highlight-end
}; };
}; };
``` ```
@ -61,15 +65,17 @@ Returns the path to the directory where the theme components can be found. When
For example, your `getThemePath` can be: For example, your `getThemePath` can be:
```js {6-8} title="my-theme/src/index.js" ```js title="my-theme/src/index.js"
const path = require('path'); const path = require('path');
module.exports = function (context, options) { module.exports = function (context, options) {
return { return {
name: 'my-theme', name: 'my-theme',
// highlight-start
getThemePath() { getThemePath() {
return path.resolve(__dirname, './theme'); return path.resolve(__dirname, './theme');
}, },
// highlight-end
}; };
}; };
``` ```
@ -88,12 +94,13 @@ You should also format these files with Prettier. Remember—JS files can and wi
Example: Example:
```js {6-13} title="my-theme/src/index.js" ```js title="my-theme/src/index.js"
const path = require('path'); const path = require('path');
module.exports = function (context, options) { module.exports = function (context, options) {
return { return {
name: 'my-theme', name: 'my-theme',
// highlight-start
getThemePath() { getThemePath() {
// Where compiled JavaScript output lives // Where compiled JavaScript output lives
return path.join(__dirname, '../lib/theme'); return path.join(__dirname, '../lib/theme');
@ -102,6 +109,7 @@ module.exports = function (context, options) {
// Where TypeScript source code lives // Where TypeScript source code lives
return path.resolve(__dirname, '../src/theme'); return path.resolve(__dirname, '../src/theme');
}, },
// highlight-end
}; };
}; };
``` ```
@ -112,7 +120,7 @@ module.exports = function (context, options) {
Returns a list of stable components that are considered safe for swizzling. These components will be swizzlable without `--danger`. All components are considered unstable by default. If an empty array is returned, all components are considered unstable. If `undefined` is returned, all components are considered stable. Returns a list of stable components that are considered safe for swizzling. These components will be swizzlable without `--danger`. All components are considered unstable by default. If an empty array is returned, all components are considered unstable. If `undefined` is returned, all components are considered stable.
```js {0-12} title="my-theme/src/index.js" ```js title="my-theme/src/index.js"
const swizzleAllowedComponents = [ const swizzleAllowedComponents = [
'CodeBlock', 'CodeBlock',
'DocSidebar', 'DocSidebar',

View file

@ -13,13 +13,15 @@ Plugins should use this lifecycle to fetch from data sources (filesystem, remote
For example, this plugin below return a random integer between 1 to 10 as content. For example, this plugin below return a random integer between 1 to 10 as content.
```js {5-6} title="docusaurus-plugin/src/index.js" ```js title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) { module.exports = function (context, options) {
return { return {
name: 'docusaurus-plugin', name: 'docusaurus-plugin',
// highlight-start
async loadContent() { async loadContent() {
return 1 + Math.floor(Math.random() * 10); return 1 + Math.floor(Math.random() * 10);
}, },
// highlight-end
}; };
}; };
``` ```
@ -75,10 +77,11 @@ export default function FriendsComponent({friends}) {
} }
``` ```
```js {4-23} title="docusaurus-friends-plugin/src/index.js" ```js title="docusaurus-friends-plugin/src/index.js"
export default function friendsPlugin(context, options) { export default function friendsPlugin(context, options) {
return { return {
name: 'docusaurus-friends-plugin', name: 'docusaurus-friends-plugin',
// highlight-start
async contentLoaded({content, actions}) { async contentLoaded({content, actions}) {
const {createData, addRoute} = actions; const {createData, addRoute} = actions;
// Create friends.json // Create friends.json
@ -99,6 +102,7 @@ export default function friendsPlugin(context, options) {
exact: true, exact: true,
}); });
}, },
// highlight-end
}; };
} }
``` ```
@ -127,10 +131,11 @@ export default function FriendsComponent() {
} }
``` ```
```js {4-14} title="docusaurus-friends-plugin/src/index.js" ```js title="docusaurus-friends-plugin/src/index.js"
export default function friendsPlugin(context, options) { export default function friendsPlugin(context, options) {
return { return {
name: 'docusaurus-friends-plugin', name: 'docusaurus-friends-plugin',
// highlight-start
async contentLoaded({content, actions}) { async contentLoaded({content, actions}) {
const {setGlobalData, addRoute} = actions; const {setGlobalData, addRoute} = actions;
// Create friends global data // Create friends global data
@ -143,6 +148,7 @@ export default function friendsPlugin(context, options) {
exact: true, exact: true,
}); });
}, },
// highlight-end
}; };
} }
``` ```
@ -280,16 +286,18 @@ interface Props {
Example: Example:
```js {4-11} title="docusaurus-plugin/src/index.js" ```js title="docusaurus-plugin/src/index.js"
module.exports = function (context, options) { module.exports = function (context, options) {
return { return {
name: 'docusaurus-plugin', name: 'docusaurus-plugin',
// highlight-start
async postBuild({siteConfig = {}, routesPaths = [], outDir}) { async postBuild({siteConfig = {}, routesPaths = [], outDir}) {
// Print out to console all the rendered routes. // Print out to console all the rendered routes.
routesPaths.map((route) => { routesPaths.map((route) => {
console.log(route); console.log(route);
}); });
}, },
// highlight-end
}; };
}; };
``` ```
@ -373,16 +381,18 @@ Returns an array of paths to the modules that are to be imported into the client
As an example, to make your theme load a `customCss` or `customJs` file path from `options` passed in by the user: As an example, to make your theme load a `customCss` or `customJs` file path from `options` passed in by the user:
```js {7-9} title="my-theme/src/index.js" ```js title="my-theme/src/index.js"
const path = require('path'); const path = require('path');
module.exports = function (context, options) { module.exports = function (context, options) {
const {customCss, customJs} = options || {}; const {customCss, customJs} = options || {};
return { return {
name: 'name-of-my-theme', name: 'name-of-my-theme',
// highlight-start
getClientModules() { getClientModules() {
return [customCss, customJs]; return [customCss, customJs];
}, },
// highlight-end
}; };
}; };
``` ```

View file

@ -28,7 +28,7 @@ To avoid mixing Joi versions, use `const {Joi} = require("@docusaurus/utils-vali
If you don't use **[Joi](https://www.npmjs.com/package/joi)** for validation you can throw an Error in case of invalid options and return options in case of success. If you don't use **[Joi](https://www.npmjs.com/package/joi)** for validation you can throw an Error in case of invalid options and return options in case of success.
```js {8-11} title="my-plugin/src/index.js" ```js title="my-plugin/src/index.js"
function myPlugin(context, options) { function myPlugin(context, options) {
return { return {
name: 'docusaurus-plugin', name: 'docusaurus-plugin',
@ -36,17 +36,19 @@ function myPlugin(context, options) {
}; };
} }
// highlight-start
myPlugin.validateOptions = ({options, validate}) => { myPlugin.validateOptions = ({options, validate}) => {
const validatedOptions = validate(myValidationSchema, options); const validatedOptions = validate(myValidationSchema, options);
return validationOptions; return validationOptions;
}; };
// highlight-end
module.exports = myPlugin; module.exports = myPlugin;
``` ```
In TypeScript, you can also choose to export this as a separate named export. In TypeScript, you can also choose to export this as a separate named export.
```ts {8-11} title="my-plugin/src/index.ts" ```ts title="my-plugin/src/index.ts"
export default function (context, options) { export default function (context, options) {
return { return {
name: 'docusaurus-plugin', name: 'docusaurus-plugin',
@ -54,10 +56,12 @@ export default function (context, options) {
}; };
} }
// highlight-start
export function validateOptions({options, validate}) { export function validateOptions({options, validate}) {
const validatedOptions = validate(myValidationSchema, options); const validatedOptions = validate(myValidationSchema, options);
return validationOptions; return validationOptions;
} }
// highlight-end
``` ```
## `validateThemeConfig({themeConfig, validate})` {#validateThemeConfig} ## `validateThemeConfig({themeConfig, validate})` {#validateThemeConfig}
@ -82,7 +86,7 @@ To avoid mixing Joi versions, use `const {Joi} = require("@docusaurus/utils-vali
If you don't use **[Joi](https://www.npmjs.com/package/joi)** for validation you can throw an Error in case of invalid options. If you don't use **[Joi](https://www.npmjs.com/package/joi)** for validation you can throw an Error in case of invalid options.
```js {8-11} title="my-theme/src/index.js" ```js title="my-theme/src/index.js"
function myPlugin(context, options) { function myPlugin(context, options) {
return { return {
name: 'docusaurus-plugin', name: 'docusaurus-plugin',
@ -90,17 +94,19 @@ function myPlugin(context, options) {
}; };
} }
// highlight-start
myPlugin.validateThemeConfig = ({themeConfig, validate}) => { myPlugin.validateThemeConfig = ({themeConfig, validate}) => {
const validatedThemeConfig = validate(myValidationSchema, options); const validatedThemeConfig = validate(myValidationSchema, options);
return validatedThemeConfig; return validatedThemeConfig;
}; };
// highlight-end
module.exports = validateThemeConfig; module.exports = validateThemeConfig;
``` ```
In TypeScript, you can also choose to export this as a separate named export. In TypeScript, you can also choose to export this as a separate named export.
```ts {8-11} title="my-theme/src/index.ts" ```ts title="my-theme/src/index.ts"
export default function (context, options) { export default function (context, options) {
return { return {
name: 'docusaurus-plugin', name: 'docusaurus-plugin',
@ -108,8 +114,10 @@ export default function (context, options) {
}; };
} }
// highlight-start
export function validateThemeConfig({themeConfig, validate}) { export function validateThemeConfig({themeConfig, validate}) {
const validatedThemeConfig = validate(myValidationSchema, options); const validatedThemeConfig = validate(myValidationSchema, options);
return validatedThemeConfig; return validatedThemeConfig;
} }
// highlight-end
``` ```

View file

@ -13,7 +13,7 @@ npm install --save @docusaurus/theme-live-codeblock
### Configuration {#configuration} ### Configuration {#configuration}
```jsx title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
plugins: ['@docusaurus/theme-live-codeblock'], plugins: ['@docusaurus/theme-live-codeblock'],
themeConfig: { themeConfig: {

View file

@ -475,7 +475,7 @@ type BlogOptions = {
Example usage: Example usage:
```js {8-11} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
presets: [ presets: [
@ -483,10 +483,12 @@ module.exports = {
'@docusaurus/preset-classic', '@docusaurus/preset-classic',
{ {
blog: { blog: {
// highlight-start
feedOptions: { feedOptions: {
type: 'all', type: 'all',
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`, copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`,
}, },
// highlight-end
}, },
}, },
], ],

View file

@ -21,10 +21,11 @@ On old browsers, the compiled output will use unsupported (too recent) JS syntax
Websites initialized with the default classic template has the following in `package.json`: Websites initialized with the default classic template has the following in `package.json`:
```json {4-11} title="package.json" ```json title="package.json"
{ {
"name": "docusaurus", "name": "docusaurus",
// ... // ...
// highlight-start
"browserslist": { "browserslist": {
"production": [">0.5%", "not dead", "not op_mini all"], "production": [">0.5%", "not dead", "not op_mini all"],
"development": [ "development": [
@ -33,6 +34,7 @@ Websites initialized with the default classic template has the following in `pac
"last 1 safari version" "last 1 safari version"
] ]
} }
// highlight-end
// ... // ...
} }
``` ```

View file

@ -124,10 +124,12 @@ For the same concern of up-to-datedness, we have stopped accepting PRs adding ne
To deploy your Docusaurus 2 sites to [Netlify](https://www.netlify.com/), first make sure the following options are properly configured: 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" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// highlight-start
url: 'https://docusaurus-2.netlify.app', // Url to your site with no trailing slash url: 'https://docusaurus-2.netlify.app', // Url to your site with no trailing slash
baseUrl: '/', // Base directory of your site relative to your repo baseUrl: '/', // Base directory of your site relative to your repo
// highlight-end
// ... // ...
}; };
``` ```
@ -228,14 +230,16 @@ GitHub Pages adds a trailing slash to Docusaurus URLs by default. It is recommen
Example: Example:
```jsx {3-6} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
url: 'https://endiliey.github.io', // Your website URL url: 'https://endiliey.github.io', // Your website URL
baseUrl: '/', baseUrl: '/',
// highlight-start
projectName: 'endiliey.github.io', projectName: 'endiliey.github.io',
organizationName: 'endiliey', organizationName: 'endiliey',
trailingSlash: false, trailingSlash: false,
// highlight-end
// ... // ...
}; };
``` ```

View file

@ -63,33 +63,40 @@ This reusable React component will manage all of your changes to the document he
Usage Example: Usage Example:
```jsx {2,5,10} ```jsx
import React from 'react'; import React from 'react';
// highlight-next-line
import Head from '@docusaurus/Head'; import Head from '@docusaurus/Head';
const MySEO = () => ( const MySEO = () => (
// highlight-start
<Head> <Head>
<meta property="og:description" content="My custom description" /> <meta property="og:description" content="My custom description" />
<meta charSet="utf-8" /> <meta charSet="utf-8" />
<title>My Title</title> <title>My Title</title>
<link rel="canonical" href="http://mysite.com/example" /> <link rel="canonical" href="http://mysite.com/example" />
</Head> </Head>
// highlight-end
); );
``` ```
Nested or latter components will override duplicate usages: Nested or latter components will override duplicate usages:
```jsx {2,5,8,11} ```jsx
<Parent> <Parent>
{/* highlight-start */}
<Head> <Head>
<title>My Title</title> <title>My Title</title>
<meta name="description" content="Helmet application" /> <meta name="description" content="Helmet application" />
</Head> </Head>
{/* highlight-end */}
<Child> <Child>
{/* highlight-start */}
<Head> <Head>
<title>Nested Title</title> <title>Nested Title</title>
<meta name="description" content="Nested component" /> <meta name="description" content="Nested component" />
</Head> </Head>
{/* highlight-end */}
</Child> </Child>
</Parent> </Parent>
``` ```
@ -111,16 +118,19 @@ The component is a wrapper around react-routers `<Link>` component that adds
External links also work, and automatically have these props: `target="_blank" rel="noopener noreferrer"`. External links also work, and automatically have these props: `target="_blank" rel="noopener noreferrer"`.
```jsx {2,7} ```jsx
import React from 'react'; import React from 'react';
// highlight-next-line
import Link from '@docusaurus/Link'; import Link from '@docusaurus/Link';
const Page = () => ( const Page = () => (
<div> <div>
<p> <p>
{/* highlight-next-line */}
Check out my <Link to="/blog">blog</Link>! Check out my <Link to="/blog">blog</Link>!
</p> </p>
<p> <p>
{/* highlight-next-line */}
Follow me on <Link to="https://twitter.com/docusaurus">Twitter</Link>! Follow me on <Link to="https://twitter.com/docusaurus">Twitter</Link>!
</p> </p>
</div> </div>
@ -147,11 +157,13 @@ Rendering a `<Redirect>` will navigate to a new location. The new location will
Example usage: Example usage:
```jsx {2,5} ```jsx
import React from 'react'; import React from 'react';
// highlight-next-line
import {Redirect} from '@docusaurus/router'; import {Redirect} from '@docusaurus/router';
const Home = () => { const Home = () => {
// highlight-next-line
return <Redirect to="/docs/test" />; return <Redirect to="/docs/test" />;
}; };
``` ```
@ -358,17 +370,20 @@ interface DocusaurusContext {
Usage example: Usage example:
```jsx {5,8-10} ```jsx
import React from 'react'; import React from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
const MyComponent = () => { const MyComponent = () => {
// highlight-next-line
const {siteConfig, siteMetadata} = useDocusaurusContext(); const {siteConfig, siteMetadata} = useDocusaurusContext();
return ( return (
<div> <div>
{/* highlight-start */}
<h1>{siteConfig.title}</h1> <h1>{siteConfig.title}</h1>
<div>{siteMetadata.siteVersion}</div> <div>{siteMetadata.siteVersion}</div>
<div>{siteMetadata.docusaurusVersion}</div> <div>{siteMetadata.docusaurusVersion}</div>
{/* highlight-end */}
</div> </div>
); );
}; };
@ -500,14 +515,17 @@ type GlobalData = Record<
Usage example: Usage example:
```jsx {2,5-7} ```jsx
import React from 'react'; import React from 'react';
// highlight-next-line
import useGlobalData from '@docusaurus/useGlobalData'; import useGlobalData from '@docusaurus/useGlobalData';
const MyComponent = () => { const MyComponent = () => {
// highlight-start
const globalData = useGlobalData(); const globalData = useGlobalData();
const myPluginData = globalData['my-plugin']['default']; const myPluginData = globalData['my-plugin']['default'];
return <div>{myPluginData.someAttribute}</div>; return <div>{myPluginData.someAttribute}</div>;
// highlight-end
}; };
``` ```
@ -531,13 +549,16 @@ function usePluginData(pluginName: string, pluginId?: string);
Usage example: Usage example:
```jsx {2,5-6} ```jsx
import React from 'react'; import React from 'react';
// highlight-next-line
import {usePluginData} from '@docusaurus/useGlobalData'; import {usePluginData} from '@docusaurus/useGlobalData';
const MyComponent = () => { const MyComponent = () => {
// highlight-start
const myPluginData = usePluginData('my-plugin'); const myPluginData = usePluginData('my-plugin');
return <div>{myPluginData.someAttribute}</div>; return <div>{myPluginData.someAttribute}</div>;
// highlight-end
}; };
``` ```
@ -551,14 +572,17 @@ useAllPluginInstancesData(pluginName: string)
Usage example: Usage example:
```jsx {2,5-7} ```jsx
import React from 'react'; import React from 'react';
// highlight-next-line
import {useAllPluginInstancesData} from '@docusaurus/useGlobalData'; import {useAllPluginInstancesData} from '@docusaurus/useGlobalData';
const MyComponent = () => { const MyComponent = () => {
// highlight-start
const allPluginInstancesData = useAllPluginInstancesData('my-plugin'); const allPluginInstancesData = useAllPluginInstancesData('my-plugin');
const myPluginData = allPluginInstancesData['default']; const myPluginData = allPluginInstancesData['default'];
return <div>{myPluginData.someAttribute}</div>; return <div>{myPluginData.someAttribute}</div>;
// highlight-end
}; };
``` ```
@ -583,10 +607,9 @@ function interpolate(
#### Example {#example-1} #### Example {#example-1}
```jsx ```js
// highlight-start // highlight-next-line
import {interpolate} from '@docusaurus/Interpolate'; import {interpolate} from '@docusaurus/Interpolate';
// highlight-end
const message = interpolate('Welcome {firstName}', {firstName: 'Sébastien'}); const message = interpolate('Welcome {firstName}', {firstName: 'Sébastien'});
``` ```
@ -620,17 +643,14 @@ function translate(
import React from 'react'; import React from 'react';
import Layout from '@theme/Layout'; import Layout from '@theme/Layout';
// highlight-start // highlight-next-line
import {translate} from '@docusaurus/Translate'; import {translate} from '@docusaurus/Translate';
// highlight-end
export default function Home() { export default function Home() {
return ( return (
<Layout <Layout
// highlight-start // highlight-next-line
title={translate({message: 'My page meta title'})} title={translate({message: 'My page meta title'})}>
// highlight-end
>
<img <img
src={'https://docusaurus.io/logo.png'} src={'https://docusaurus.io/logo.png'}
aria-label={ aria-label={
@ -666,7 +686,7 @@ For React rendering logic, use [`useIsBrowser()`](#useIsBrowser) or [`<BrowserOn
Example: Example:
```jsx ```js
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
if (ExecutionEnvironment.canUseDOM) { if (ExecutionEnvironment.canUseDOM) {
@ -685,7 +705,7 @@ if (ExecutionEnvironment.canUseDOM) {
A module exposing useful constants to client-side theme code. A module exposing useful constants to client-side theme code.
```jsx ```js
import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants'; import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants';
``` ```

View file

@ -134,10 +134,11 @@ You can delete/remove versions as well.
Example: Example:
```diff {4} ```diff
[ [
"2.0.0", "2.0.0",
"1.9.0", "1.9.0",
// highlight-next-line
- "1.8.0" - "1.8.0"
] ]
``` ```

View file

@ -131,15 +131,17 @@ html[data-theme='dark'] .themedDocusaurus [fill='#FFFF50'] {
Docusaurus supports themed images: the `ThemedImage` component (included in the themes) allows you to switch the image source based on the current theme. Docusaurus supports themed images: the `ThemedImage` component (included in the themes) allows you to switch the image source based on the current theme.
```jsx {5-8} ```jsx
import ThemedImage from '@theme/ThemedImage'; import ThemedImage from '@theme/ThemedImage';
<ThemedImage <ThemedImage
alt="Docusaurus themed image" alt="Docusaurus themed image"
// highlight-start
sources={{ sources={{
light: useBaseUrl('/img/docusaurus_light.svg'), light: useBaseUrl('/img/docusaurus_light.svg'),
dark: useBaseUrl('/img/docusaurus_dark.svg'), dark: useBaseUrl('/img/docusaurus_dark.svg'),
}} }}
// highlight-end
/>; />;
``` ```

View file

@ -34,7 +34,7 @@ function HelloCodeTitle(props) {
Code blocks are text blocks wrapped around by strings of 3 backticks. You may check out [this reference](https://github.com/mdx-js/specification) for the specifications of MDX. Code blocks are text blocks wrapped around by strings of 3 backticks. You may check out [this reference](https://github.com/mdx-js/specification) for the specifications of MDX.
```jsx ```js
console.log('Every repo must come with a mascot.'); console.log('Every repo must come with a mascot.');
``` ```
@ -44,7 +44,7 @@ Use the matching language meta string for your code block, and Docusaurus will p
<BrowserWindow> <BrowserWindow>
```jsx ```js
console.log('Every repo must come with a mascot.'); console.log('Every repo must come with a mascot.');
``` ```
@ -56,10 +56,11 @@ By default, the Prism [syntax highlighting theme](https://github.com/FormidableL
For example, if you prefer to use the `dracula` highlighting theme: For example, if you prefer to use the `dracula` highlighting theme:
```js {4} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
themeConfig: { themeConfig: {
prism: { prism: {
// highlight-next-line
theme: require('prism-react-renderer/themes/dracula'), theme: require('prism-react-renderer/themes/dracula'),
}, },
}, },
@ -80,11 +81,12 @@ To add syntax highlighting for any of the other [Prism-supported languages](http
For example, if you want to add highlighting for the PowerShell language: For example, if you want to add highlighting for the PowerShell language:
```js {5} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
themeConfig: { themeConfig: {
prism: { prism: {
// highlight-next-line
additionalLanguages: ['powershell'], additionalLanguages: ['powershell'],
}, },
// ... // ...
@ -102,14 +104,15 @@ npm run swizzle @docusaurus/theme-classic prism-include-languages
It will produce `prism-include-languages.js` in your `src/theme` folder. You can add highlighting support for custom languages by editing `prism-include-languages.js`: It will produce `prism-include-languages.js` in your `src/theme` folder. You can add highlighting support for custom languages by editing `prism-include-languages.js`:
```js {8} title="src/theme/prism-include-languages.js" ```js title="src/theme/prism-include-languages.js"
const prismIncludeLanguages = (Prism) => { const prismIncludeLanguages = (Prism) => {
// ... // ...
additionalLanguages.forEach((lang) => { additionalLanguages.forEach((lang) => {
require(`prismjs/components/prism-${lang}`); // eslint-disable-line require(`prismjs/components/prism-${lang}`);
}); });
// highlight-next-line
require('/path/to/your/prism-language-definition'); require('/path/to/your/prism-language-definition');
// ... // ...
@ -124,7 +127,7 @@ You can refer to [Prism's official language definitions](https://github.com/Pris
You can use comments with `highlight-next-line`, `highlight-start`, and `highlight-end` to select which lines are highlighted. You can use comments with `highlight-next-line`, `highlight-start`, and `highlight-end` to select which lines are highlighted.
```jsx ```js
function HighlightSomeText(highlight) { function HighlightSomeText(highlight) {
if (highlight) { if (highlight) {
// highlight-next-line // highlight-next-line
@ -148,7 +151,7 @@ You can use comments with `highlight-next-line`, `highlight-start`, and `highlig
````mdx-code-block ````mdx-code-block
<BrowserWindow> <BrowserWindow>
```jsx ```js
function HighlightSomeText(highlight) { function HighlightSomeText(highlight) {
if (highlight) { if (highlight) {
// highlight-next-line // highlight-next-line
@ -348,9 +351,10 @@ By default, all React imports are available. If you need more imports available,
npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope
``` ```
```jsx {3-15,21} title="src/theme/ReactLiveScope/index.js" ```jsx title="src/theme/ReactLiveScope/index.js"
import React from 'react'; import React from 'react';
// highlight-start
const ButtonExample = (props) => ( const ButtonExample = (props) => (
<button <button
{...props} {...props}
@ -365,11 +369,13 @@ const ButtonExample = (props) => (
}} }}
/> />
); );
// highlight-end
// Add react-live imports you need here // Add react-live imports you need here
const ReactLiveScope = { const ReactLiveScope = {
React, React,
...React, ...React,
// highlight-next-line
ButtonExample, ButtonExample,
}; };
@ -392,15 +398,14 @@ function MyPlayground(props) {
</BrowserWindow> </BrowserWindow>
## Using JSX markup in code blocks {using-jsx-markup} ## Using JSX markup in code blocks {#using-jsx-markup}
Code block in Markdown always preserves its content as plain text, meaning you can't do something like: Code block in Markdown always preserves its content as plain text, meaning you can't do something like:
```ts ```ts
type EditUrlFunction = (params: { type EditUrlFunction = (params: {
version: string;
// This doesn't turn into a link (for good reason!) // This doesn't turn into a link (for good reason!)
// See <a href="/docs/versioning">doc versioning</a> version: <a href="/docs/versioning">Version</a>;
versionDocsDirPath: string; versionDocsDirPath: string;
docPath: string; docPath: string;
permalink: string; permalink: string;

View file

@ -93,7 +93,7 @@ module.exports = {
Some plugins can be configured and accept their own options. In that case, use the `[plugin, pluginOptions]` syntax, like this: Some plugins can be configured and accept their own options. In that case, use the `[plugin, pluginOptions]` syntax, like this:
```jsx title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
presets: [ presets: [
[ [
@ -150,7 +150,7 @@ module.exports = plugin;
You can now import your plugin in `docusaurus.config.js` and use it just like an installed plugin! You can now import your plugin in `docusaurus.config.js` and use it just like an installed plugin!
```jsx title="docusaurus.config.js" ```js title="docusaurus.config.js"
// highlight-next-line // highlight-next-line
const sectionPrefix = require('./src/remark/section-prefix'); const sectionPrefix = require('./src/remark/section-prefix');
@ -173,7 +173,7 @@ module.exports = {
The default plugins of Docusaurus would operate before the custom remark plugins, and that means the images or links have been converted to JSX with `require()` calls already. For example, in the example above, the table of contents generated is still the same even when all `h2` headings are now prefixed by `Section X.`, because the TOC-generating plugin is called before our custom plugin. If you need to process the MDAST before the default plugins do, use the `beforeDefaultRemarkPlugins` and `beforeDefaultRehypePlugins`. The default plugins of Docusaurus would operate before the custom remark plugins, and that means the images or links have been converted to JSX with `require()` calls already. For example, in the example above, the table of contents generated is still the same even when all `h2` headings are now prefixed by `Section X.`, because the TOC-generating plugin is called before our custom plugin. If you need to process the MDAST before the default plugins do, use the `beforeDefaultRemarkPlugins` and `beforeDefaultRehypePlugins`.
```jsx title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
presets: [ presets: [
[ [

View file

@ -135,7 +135,7 @@ In Docusaurus 2, we split each functionality (blog, docs, pages) into plugins fo
Add the following preset configuration to your `docusaurus.config.js`. Add the following preset configuration to your `docusaurus.config.js`.
```jsx title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
presets: [ presets: [
@ -217,7 +217,7 @@ import ColorGenerator from '@site/src/components/ColorGenerator';
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`: 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" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
themeConfig: { themeConfig: {
@ -251,7 +251,7 @@ headerLinks: [
Now, these two fields are both handled by the theme: Now, these two fields are both handled by the theme:
```jsx {6-19} title="docusaurus.config.js" ```js {6-19} title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
themeConfig: { themeConfig: {
@ -279,7 +279,7 @@ module.exports = {
#### `algolia` {#algolia} #### `algolia` {#algolia}
```jsx {4-8} title="docusaurus.config.js" ```js {4-8} title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
themeConfig: { themeConfig: {
@ -305,7 +305,7 @@ You can contact the DocSearch team (@shortcuts, @s-pace) for support. They can u
Deprecated. Pass it as a blog option to `@docusaurus/preset-classic` instead: Deprecated. Pass it as a blog option to `@docusaurus/preset-classic` instead:
```jsx {8} title="docusaurus.config.js" ```js {8} title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
presets: [ presets: [
@ -332,7 +332,7 @@ Deprecated. Create a `CNAME` file in your `static` folder instead with your cust
Deprecated. Pass it as an option to `@docusaurus/preset-classic` docs instead: Deprecated. Pass it as an option to `@docusaurus/preset-classic` docs instead:
```jsx {8-20} title="docusaurus.config.js" ```js {8-20} title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
presets: [ presets: [
@ -363,7 +363,7 @@ module.exports = {
#### `gaTrackingId` {#gatrackingid} #### `gaTrackingId` {#gatrackingid}
```jsx {5} title="docusaurus.config.js" ```js {5} title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
themeConfig: { themeConfig: {
@ -377,7 +377,7 @@ module.exports = {
#### `gaGtag` {#gagtag} #### `gaGtag` {#gagtag}
```jsx {5} title="docusaurus.config.js" ```js {5} title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
themeConfig: { themeConfig: {

View file

@ -15,20 +15,22 @@ npm install --save @docusaurus/preset-classic
Then, add it in your site's `docusaurus.config.js`'s `presets` option: Then, add it in your site's `docusaurus.config.js`'s `presets` option:
```jsx {3} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
// highlight-next-line
presets: ['@docusaurus/preset-classic'], presets: ['@docusaurus/preset-classic'],
}; };
``` ```
To load presets from your local directory, specify how to resolve them: To load presets from your local directory, specify how to resolve them:
```jsx {5} title="docusaurus.config.js" ```js title="docusaurus.config.js"
const path = require('path'); const path = require('path');
module.exports = { module.exports = {
// ... // ...
// highlight-next-line
presets: [path.resolve(__dirname, '/path/to/docusaurus-local-presets')], presets: [path.resolve(__dirname, '/path/to/docusaurus-local-presets')],
}; };
``` ```
@ -48,18 +50,22 @@ module.exports = function preset(context, opts = {}) {
then in your Docusaurus config, you may configure the preset instead: then in your Docusaurus config, you may configure the preset instead:
```jsx {3} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
presets: [ presets: [
// highlight-start
[
'@docusaurus/preset-my-own', '@docusaurus/preset-my-own',
{cool: {hello: 'world'}, blog: {path: '/blog'}}, {cool: {hello: 'world'}, blog: {path: '/blog'}},
], ],
// highlight-end
],
}; };
``` ```
This is equivalent of doing: This is equivalent of doing:
```jsx title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
themes: ['@docusaurus/themes-cool', {hello: 'world'}], themes: ['@docusaurus/themes-cool', {hello: 'world'}],
plugins: ['@docusaurus/plugin-blog', {path: '/blog'}], plugins: ['@docusaurus/plugin-blog', {path: '/blog'}],

View file

@ -86,7 +86,7 @@ module.exports = {
Then, add an `algolia` field in your `themeConfig`. **[Apply for DocSearch](https://docsearch.algolia.com/apply/)** to get your Algolia index and API key. Then, 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" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
themeConfig: { themeConfig: {
@ -142,7 +142,7 @@ To solve this problem, the contextual search feature understands that you are br
- browsing `/docs/v1/myDoc`, search results will only include **v1** docs (+ other unversioned pages) - browsing `/docs/v1/myDoc`, search results will only include **v1** docs (+ other unversioned pages)
- browsing `/docs/v2/myDoc`, search results will only include **v2** docs (+ other unversioned pages) - browsing `/docs/v2/myDoc`, search results will only include **v2** docs (+ other unversioned pages)
```jsx title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
themeConfig: { themeConfig: {

View file

@ -172,9 +172,10 @@ npm install --save docusaurus-plugin-sass sass
2. Include the plugin in your `docusaurus.config.js` file: 2. Include the plugin in your `docusaurus.config.js` file:
```js {3} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
// highlight-next-line
plugins: ['docusaurus-plugin-sass'], plugins: ['docusaurus-plugin-sass'],
// ... // ...
}; };
@ -186,7 +187,7 @@ module.exports = {
You can now set the `customCss` property of `@docusaurus/preset-classic` to point to your Sass/SCSS file: You can now set the `customCss` property of `@docusaurus/preset-classic` to point to your Sass/SCSS file:
```js {8} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
presets: [ presets: [
[ [
@ -194,6 +195,7 @@ module.exports = {
{ {
// ... // ...
theme: { theme: {
// highlight-next-line
customCss: [require.resolve('./src/css/custom.scss')], customCss: [require.resolve('./src/css/custom.scss')],
}, },
// ... // ...

View file

@ -19,20 +19,22 @@ npm install --save docusaurus-plugin-name
Then you add it in your site's `docusaurus.config.js`'s `plugins` option: Then you add it in your site's `docusaurus.config.js`'s `plugins` option:
```jsx {3} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
// highlight-next-line
plugins: ['@docusaurus/plugin-content-pages'], plugins: ['@docusaurus/plugin-content-pages'],
}; };
``` ```
Docusaurus can also load plugins from your local directory, you can do something like the following: Docusaurus can also load plugins from your local directory, you can do something like the following:
```jsx {5} title="docusaurus.config.js" ```js title="docusaurus.config.js"
const path = require('path'); const path = require('path');
module.exports = { module.exports = {
// ... // ...
// highlight-next-line
plugins: [path.resolve(__dirname, '/path/to/docusaurus-local-plugin')], plugins: [path.resolve(__dirname, '/path/to/docusaurus-local-plugin')],
}; };
``` ```
@ -43,16 +45,18 @@ For the most basic usage of plugins, you can provide just the plugin name or the
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`. 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" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
plugins: [ plugins: [
// highlight-start
[ [
'@docusaurus/plugin-xxx', '@docusaurus/plugin-xxx',
{ {
/* options */ /* options */
}, },
], ],
// highlight-end
], ],
}; };
``` ```
@ -78,20 +82,15 @@ module.exports = {
## Multi-instance plugins and plugin ids {#multi-instance-plugins-and-plugin-ids} ## Multi-instance plugins and plugin ids {#multi-instance-plugins-and-plugin-ids}
All Docusaurus content plugins can support multiple plugin instances. All Docusaurus content plugins can support multiple plugin instances. The Docs plugin has [additional multi-instance documentation](./guides/docs/docs-multi-instance.mdx). It is required to assign a unique id to each plugin instance, and by default, the plugin id is `default`.
The Docs plugin has [additional multi-instance documentation](./guides/docs/docs-multi-instance.mdx) ```js title="docusaurus.config.js"
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 = { module.exports = {
plugins: [ plugins: [
[ [
'@docusaurus/plugin-xxx', '@docusaurus/plugin-xxx',
{ {
// highlight-next-line
id: 'plugin-xxx-1', id: 'plugin-xxx-1',
// other options // other options
}, },
@ -99,6 +98,7 @@ module.exports = {
[ [
'@docusaurus/plugin-xxx', '@docusaurus/plugin-xxx',
{ {
// highlight-next-line
id: 'plugin-xxx-2', id: 'plugin-xxx-2',
// other options // other options
}, },

View file

@ -39,9 +39,10 @@ We maintain a [list of official themes](./api/themes/overview.md).
To use themes, specify the themes in your `docusaurus.config.js`. You may use multiple themes: To use themes, specify the themes in your `docusaurus.config.js`. You may use multiple themes:
```js {3} title="docusaurus.config.js" ```js title="docusaurus.config.js"
module.exports = { module.exports = {
// ... // ...
// highlight-next-line
themes: ['@docusaurus/theme-classic', '@docusaurus/theme-live-codeblock'], themes: ['@docusaurus/theme-classic', '@docusaurus/theme-live-codeblock'],
}; };
``` ```
@ -228,14 +229,16 @@ To summarize:
A Docusaurus theme normally includes an `index.js` file where you hook up to the lifecycle methods, alongside a `theme/` directory of components. A typical Docusaurus `theme` folder looks like this: A Docusaurus theme normally includes an `index.js` file where you hook up to the lifecycle methods, alongside a `theme/` directory of components. A typical Docusaurus `theme` folder looks like this:
```bash {5-7} ```bash
website website
├── package.json ├── package.json
└── src └── src
├── index.js ├── index.js
# highlight-start
└── theme └── theme
├── MyThemeComponent ├── MyThemeComponent
└── AnotherThemeComponent.js └── AnotherThemeComponent.js
# highlight-end
``` ```
There are two lifecycle methods that are essential to theme implementation: There are two lifecycle methods that are essential to theme implementation: