跳到主要内容
版本:2.4.3

代码块

文档中的代码块超级厉害 💪。

Code title

You can add a title to the code block by adding a title key after the language (leave a space between them).

```jsx title="/src/components/HelloCodeTitle.js"
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
```
http://localhost:3000
/src/components/HelloCodeTitle.js
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}

Syntax highlighting

代码块是使用 3 个反引号包裹的文本块。 You may check out this reference for the specifications of MDX.

```js
console.log('每个仓库都应该有个吉祥物。');
```

Use the matching language meta string for your code block, and Docusaurus will pick up syntax highlighting automatically, powered by Prism React Renderer.

http://localhost:3000
console.log('每个仓库都应该有个吉祥物。');

Theming

By default, the Prism syntax highlighting theme we use is Palenight. 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:

docusaurus.config.js
module.exports = {
themeConfig: {
prism: {
theme: require('prism-react-renderer/themes/dracula'),
},
},
};

因为每个 Prism 主题都只是一个 JS 对象,所以如果你对默认值不满意,也可以写一个自己的主题。 Docusaurus enhances the github and vsDark themes to provide richer highlight, and you can check our implementations for the light and dark code block themes.

Supported Languages

By default, Docusaurus comes with a subset of commonly used languages.

注意

一些流行语言,包括 Java、C#、PHP 在内,默认未启用。

To add syntax highlighting for any of the other Prism-supported languages, define it in an array of additional languages.

备注

每个附加语言都必须是有效的 Prism 组件名称。 For example, Prism would map the language cs to csharp, but only prism-csharp.js exists as a component, so you need to use additionalLanguages: ['csharp']. You can look into node_modules/prismjs/components to find all components (languages) available.

举个例子,如果你想要支持 PowerShell 语言的高亮:

docusaurus.config.js
module.exports = {
// ...
themeConfig: {
prism: {
additionalLanguages: ['powershell'],
},
// ...
},
};

After adding additionalLanguages, restart Docusaurus.

If you want to add highlighting for languages not yet supported by Prism, you can swizzle prism-include-languages:

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:

src/theme/prism-include-languages.js
const prismIncludeLanguages = (Prism) => {
// ...

additionalLanguages.forEach((lang) => {
require(`prismjs/components/prism-${lang}`);
});

require('/path/to/your/prism-language-definition');

// ...
};

You can refer to Prism's official language definitions when you are writing your own language definitions.

Line highlighting

Highlighting with comments

You can use comments with highlight-next-line, highlight-start, and highlight-end to select which lines are highlighted.

```js
function HighlightSomeText(highlight) {
if (highlight) {
// highlight-next-line
return '这行被高亮了!';
}

return '这里不会';
}

function HighlightMoreText(highlight) {
// highlight-start
if (highlight) {
return '这块被高亮了!';
}
// highlight-end

return '这里不会';
}
```
http://localhost:3000
function HighlightSomeText(highlight) {
if (highlight) {
return '这行被高亮了!';
}

return '这里不会';
}

function HighlightMoreText(highlight) {
if (highlight) {
return '这段被高亮了!';
}

return '这里不会';
}

受支持的注释语法:

样式语法
C 样式/* ... */ and // ...
JSX 样式{/* ... */}
Bash 样式# ...
HTML 样式<!-- ... -->

We will do our best to infer which set of comment styles to use based on the language, and default to allowing all comment styles. 如果有任何注释风格暂时没有被支持,我们乐意去添加对它们的支持。 欢迎发起拉取请求。 需要注意的是,不同注释风格不会有语义上的差别,只会有内容上的。

You can set your own background color for highlighted code line in your src/css/custom.css which will better fit to your selected syntax highlighting theme. 下方的颜色适用于默认的语法高亮主题(Palenight)。如果你使用其他的主题,也需要做出相应的颜色调整。

/src/css/custom.css
:root {
--docusaurus-highlighted-code-line-bg: rgb(72, 77, 91);
}

/* If you have a different syntax highlighting theme for dark mode. */
[data-theme='dark'] {
/* Color which works with dark mode syntax highlighting theme */
--docusaurus-highlighted-code-line-bg: rgb(100, 100, 100);
}

If you also need to style the highlighted code line in some other way, you can target on theme-code-block-highlighted-line CSS class.

Highlighting with metadata string

你也可以在元数据字符串中指定高亮行的范围(需要在语言种类后留一个空格)。 要高亮多行内容,请使用英文半角逗号来分隔行号,或使用范围语法来选择多行代码块以高亮。 This feature uses the parse-number-range library and you can find more syntax on their project details.

```jsx {1,4-6,11}
import React from 'react';

function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}

return <div>Foo</div>;
}

export default MyComponent;
```
http://localhost:3000
import React from 'react';

function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}

return <div>Foo</div>;
}

export default MyComponent;
prefer comments

推荐你使用注释来实现语法高亮。 如果你把通过内嵌的注释来高亮代码,你就不需要在代码块内容很长时手动去数代码行数了。 即使你添加/删除了某几行,你也不需要去调整行号的偏移范围。

- ```jsx {3}
+ ```jsx {4}
function HighlightSomeText(highlight) {
if (highlight) {
+ console.log('找到了高亮文本');
return '这个文本高亮了!';
}

return '没啥被高亮了';
}
```

下面我们将介绍可扩展的魔法注释是如何实现自定义指令及和功能的。 只有在不使用元数据字符串的数字范围时,魔法注释才会被解析。

Custom magic comments

// highlight-next-line and // highlight-start etc. are called "magic comments", because they will be parsed and removed, and their purposes are to add metadata to the next line, or the section that the pair of start- and end-comments enclose.

你可以通过主题配置来设定你的自定义魔法注释。 For example, you can register another magic comment that adds a code-block-error-line class name:

module.exports = {
themeConfig: {
prism: {
magicComments: [
// Remember to extend the default highlight class name as well!
{
className: 'theme-code-block-highlighted-line',
line: 'highlight-next-line',
block: {start: 'highlight-start', end: 'highlight-end'},
},
{
className: 'code-block-error-line',
line: 'This will error',
},
],
},
},
};
http://localhost:3000

在 JavaScript 中,试图访问 null 的属性会报错。

const name = null;
console.log(name.toUpperCase());
// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase')

If you use number ranges in metastring (the {1,3-4} syntax), Docusaurus will apply the first magicComments entry's class name. This, by default, is theme-code-block-highlighted-line, but if you change the magicComments config and use a different entry as the first one, the meaning of the metastring range will change as well.

You can disable the default line highlighting comments with magicComments: []. 如果魔法注释的配置是空数组,但使用了一个包含数字范围的代码块时,Docusaurus 就会报错,因为没有可以应用给类名的配置项——高亮的类名毕竟只是一个魔法注释配置的项目而已。

Every magic comment entry will contain three keys: className (required), line, which applies to the directly next line, or block (containing start and end), which applies to the entire block enclosed by the two comments.

Using CSS to target the class can already do a lot, but you can unlock the full potential of this feature through swizzling.

npm run swizzle @docusaurus/theme-classic CodeBlock/Line

The Line component will receive the list of class names, based on which you can conditionally render different markup.

Line numbering

You can enable line numbering for your code block by using showLineNumbers key within the language meta string (don't forget to add space directly before the key).

```jsx {1,4-6,11} showLineNumbers
import React from 'react';

function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}

return <div>Foo</div>;
}

export default MyComponent;
```
http://localhost:3000
import React from 'react';

function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}

return <div>Foo</div>;
}

export default MyComponent;

Interactive code editor

(Powered by React Live)

You can create an interactive coding editor with the @docusaurus/theme-live-codeblock plugin. 首先,将插件添加到您的项目依赖。

npm install --save @docusaurus/theme-live-codeblock

You will also need to add the plugin to your docusaurus.config.js.

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(() => {
const timerID = setInterval(() => tick(), 1000);

return function cleanup() {
clearInterval(timerID);
};
});

function tick() {
setDate(new Date());
}

return (
<div>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
```

这个代码块会被渲染成一个可交互的代码编辑器。 代码的变更结果将会实时显示在结果的预览区域。

http://localhost:3000
实时编辑器
function Clock(props) {
  const [date, setDate] = useState(new Date());
  useEffect(() => {
    const timerID = setInterval(() => tick(), 1000);

    return function cleanup() {
      clearInterval(timerID);
    };
  });

  function tick() {
    setDate(new Date());
  }

  return (
    <div>
      <h2>It is {date.toLocaleTimeString()}.</h2>
    </div>
  );
}
结果
Loading...

Imports

react-live and imports

你不能从 react-live 的代码编辑器中直接导入组件。你得显式地预先定义好所有组件导入项。

默认情况下,你可以使用 React 的所有导入项。 如果你需要更多可导入项,你通过 swizzle 组件 react-live scope 来获取:

npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope -- --eject
src/theme/ReactLiveScope/index.js
import React from 'react';

const ButtonExample = (props) => (
<button
{...props}
style={{
backgroundColor: 'white',
color: 'black',
border: 'solid red',
borderRadius: 20,
padding: 10,
cursor: 'pointer',
...props.style,
}}
/>
);

// Add react-live imports you need here
const ReactLiveScope = {
React,
...React,
ButtonExample,
};

export default ReactLiveScope;

The ButtonExample component is now available to use:

http://localhost:3000
实时编辑器
function MyPlayground(props) {
  return (
    <div>
      <ButtonExample onClick={() => alert('hey!')}>Click me</ButtonExample>
    </div>
  );
}
结果
Loading...

命令式渲染 (noInline)

The noInline option should be used to avoid errors when your code spans multiple components or variables.

```jsx live noInline
const project = 'Docusaurus';

const Greeting = () => <p>Hello {project}!</p>;

render(<Greeting />);
```

Unlike an ordinary interactive code block, when using noInline React Live won't wrap your code in an inline function to render it.

You will need to explicitly call render() at the end of your code to display the output.

http://localhost:3000
实时编辑器
const project = "Docusaurus";

const Greeting = () => (
  <p>Hello {project}!</p>
);

render(
  <Greeting />
);
结果
Loading...

Using JSX markup in code blocks

Markdown 中的代码块总是将其内容作为纯文本保留,这意味着你不能像下面这样这么写:

type EditUrlFunction = (params: {
// This doesn't turn into a link (for good reason!)
version: <a href="/docs/versioning">Version</a>;
versionDocsDirPath: string;
docPath: string;
permalink: string;
locale: string;
}) => string | undefined;

If you want to embed HTML markup such as anchor links or bold type, you can use the <pre> tag, <code> tag, or <CodeBlock> component.

<pre>
<b>Input: </b>1 2 3 4{'\n'}
<b>Output: </b>"366300745"{'\n'}
</pre>
http://localhost:3000
Input: 1 2 3 4
Output: "366300745"
MDX is whitespace insensitive

MDX is in line with JSX behavior: line break characters, even when inside <pre>, are turned into spaces. 你必须显式地写一个换行符,它才会真的显示成换行效果。

注意

语法高亮只适用于纯字符串。 Docusaurus 不会试图解析代码块里包含的 JSX 子元素中的内容。

Multi-language support code blocks

你可以通过 MDX 的能力在文档中创造可交互的组件。例如,你可以用选项卡组件来切换并展示包含多种编程语言的代码示例。

Instead of implementing a dedicated component for multi-language support code blocks, we've implemented a general-purpose <Tabs> component in the classic theme so that you can use it for other non-code scenarios as well.

下面的例子介绍了如何在文档中使用选项卡展示多个编程语言的代码块。 Note that the empty lines above and below each language block are intentional. This is a current limitation of MDX: you have to leave empty lines around Markdown syntax for the MDX parser to know that it's Markdown syntax and not JSX.

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

<Tabs>
<TabItem value="js" label="JavaScript">

```js
function helloWorld() {
console.log('Hello, world!');
}
```

</TabItem>
<TabItem value="py" label="Python">

```py
def hello_world():
print("Hello, world!")
```

</TabItem>
<TabItem value="java" label="Java">

```java
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
```

</TabItem>
</Tabs>

你将看到以下的效果:

http://localhost:3000
function helloWorld() {
console.log('Hello, world!');
}

If you have multiple of these multi-language code tabs, and you want to sync the selection across the tab instances, refer to the Syncing tab choices section.

Docusaurus npm2yarn remark plugin

需要同时显示 npm 和 Yarn 的 CLI 命令很常见,比如:

npm install @docusaurus/remark-plugin-npm2yarn

Docusaurus provides such a utility out of the box, freeing you from using the Tabs component every time. To enable this feature, first install the @docusaurus/remark-plugin-npm2yarn package as above, and then in docusaurus.config.js, for the plugins where you need this feature (doc, blog, pages, etc.), register it in the remarkPlugins option. (See Docs configuration for more details on configuration format)

docusaurus.config.js
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
remarkPlugins: [
[require('@docusaurus/remark-plugin-npm2yarn'), {sync: true}],
],
},
pages: {
remarkPlugins: [require('@docusaurus/remark-plugin-npm2yarn')],
},
blog: {
remarkPlugins: [
[
require('@docusaurus/remark-plugin-npm2yarn'),
{converters: ['pnpm']},
],
],
// ...
},
},
],
],
};

And then use it by adding the npm2yarn key to the code block:

```bash npm2yarn
npm install @docusaurus/remark-plugin-npm2yarn
```

Configuration

选项类型默认值描述
syncbooleanfalseWhether to sync the selected converter across all code blocks.
convertersarray'yarn', 'pnpm'The list of converters to use. The order of the converters is important, as the first converter will be used as the default choice.

Usage in JSX

Outside of Markdown, you can use the @theme/CodeBlock component to get the same output.

import CodeBlock from '@theme/CodeBlock';

export default function MyReactPage() {
return (
<div>
<CodeBlock
language="jsx"
title="/src/components/HelloCodeTitle.js"
showLineNumbers>
{`function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}`}
</CodeBlock>
</div>
);
}
http://localhost:3000
/src/components/HelloCodeTitle.js
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}

The props accepted are language, title and showLineNumbers, in the same way as you write Markdown code blocks.

Although discouraged, you can also pass in a metastring prop like metastring='{1-2} title="/src/components/HelloCodeTitle.js" showLineNumbers', which is how Markdown code blocks are handled under the hood. However, we recommend you use comments for highlighting lines.

As previously stated, syntax highlighting is only applied when the children is a simple string.