跳到主要内容

代码块

文档中加入代码块 Code blocks within documentation are super-powered 💪.

代码的标题#

你可以在编程语言的标记后面(别忘还要添加一个空格)添加 title 关键字来为代码块添加标题。

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

语法高亮#

代码块是由 3 个反引号(backticks)引起来的文本块。你可以查看 此手册 了解 MDX 的规范。

```jsx
console.log('Every repo must come with a mascot.');
```

通过匹配代码块的编程语言标记,Docusaurus 能够自动使用 Prism React Renderer 来为代码添加高亮显示。

console.log('Every repo must come with a mascot.');

我们默认使用 Prism 的 Palenight 语法高亮主题。你可在 docusaurus.config.js 配置文件中的 themeConfig 配置项中为 prism 字段设置 theme 属性即可更改为另一个主题。

例如,如果你更喜欢使用 dracula 高亮主题的话,配置如下:

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

默认情况下,Docusaurus 自动支持部分 常用编程语言

要为其它 Prism 所支持的编程语言 添加语法高亮的话,请将它们添加到 additionalLanguages 配置项中。

例如,要为 powershell 编程语言添加语法高亮的话,配置如下:

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

如果要为 Prism 尚不支持的编程语言添加语法高亮的话,则可以覆盖(swizzle)prism-include-languages 组件:

npm run swizzle @docusaurus/theme-classic prism-include-languages

这将在你的 src/theme 目录下生成 prism-include-languages.js 文件。你可以通过编辑 prism-include-languages.js 文件来添加对新的编程语言的语法高亮的支持。

src/theme/prism-include-languages.js
const prismIncludeLanguages = (Prism) => {
// ...
additionalLanguages.forEach((lang) => {
require(`prismjs/components/prism-${lang}`); // eslint-disable-line
});
require('/path/to/your/prism-language-definition');
// ...
};

在你为新的编程语言添加语法高亮功能时,可以参考 Prism 官方的语言定义

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';
}
```
function HighlightSomeText(highlight) {
if (highlight) {
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}

To accomplish this, Docusaurus adds the docusaurus-highlight-code-line class to the highlighted lines. You will need to define your own styling for this CSS, possibly in your src/css/custom.css with a custom background color which is dependent on your selected syntax highlighting theme. The color given below works for the default highlighting theme (Palenight), so if you are using another theme, you will have to tweak the color accordingly.

/src/css/custom.css
.docusaurus-highlight-code-line {
background-color: rgb(72, 77, 91);
display: block;
margin: 0 calc(-1 * var(--ifm-pre-padding));
padding: 0 var(--ifm-pre-padding);
}
/* If you have a different syntax highlighting theme for dark mode. */
html[data-theme='dark'] .docusaurus-highlight-code-line {
background-color: ; /* Color which works with dark mode syntax highlighting theme */
}

To highlight multiple lines, separate the line numbers by commas or use the range syntax to select a chunk of lines. This feature uses the parse-number-range library and you can find more syntax 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;
```
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;

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

```jsx
function HighlightSomeText(highlight) {
if (highlight) {
// highlight-next-line
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
function HighlightMoreText(highlight) {
// highlight-start
if (highlight) {
return 'This range is highlighted!';
}
// highlight-end
return 'Nothing highlighted';
}
```
function HighlightSomeText(highlight) {
if (highlight) {
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
function HighlightMoreText(highlight) {
if (highlight) {
return 'This range is highlighted!';
}
return 'Nothing highlighted';
}

Supported commenting syntax:

LanguageSyntax
JavaScript/* ... */ and // ...
JSX{/* ... */}
Python# ...
HTML<!-- ... -->

If there's a syntax that is not currently supported, we are open to adding them! Pull requests welcome.

Interactive code editor#

(Powered by React Live)

You can create an interactive coding editor with the @docusaurus/theme-live-codeblock plugin.

First, add the plugin to your package.

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(() => {
var timerID = setInterval(() => tick(), 1000);
return function cleanup() {
clearInterval(timerID);
};
});
function tick() {
setDate(new Date());
}
return (
<div>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
```

The code block will be rendered as an interactive editor. Changes to the code will reflect on the result panel live.

实时编辑器
结果
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

Imports#

react-live and imports

It is not possible to import components directly from the react-live code editor, you have to define available imports upfront.

By default, all React imports are available. If you need more imports available, swizzle the react-live scope:

npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope
src/theme/ReactLiveScope/index.js
import React from 'react';
const ButtonExample = (props) => (
<button
{...props}
style={{
backgroundColor: 'white',
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:

实时编辑器
结果
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

Multi-language support code blocks#

With MDX, you can easily create interactive components within your documentation, for example, to display code in multiple programming languages and switching between them using a tabs component.

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

The following example is how you can have multi-language code tabs in your docs. Note that the empty lines above and below each language block is intentional. This is a current limitation of MDX, you have to leave empty lines around Markdown syntax for the MDX parser to know that it's Markdown syntax and not JSX.

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs
defaultValue="js"
values={[
{ label: 'JavaScript', value: 'js', },
{ label: 'Python', value: 'py', },
{ label: 'Java', value: 'java', },
]
}>
<TabItem value="js">
```js
function helloWorld() {
console.log('Hello, world!');
}
```
</TabItem>
<TabItem value="py">
```py
def hello_world():
print 'Hello, world!'
```
</TabItem>
<TabItem value="java">
```java
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
```
</TabItem>
</Tabs>

And you will get the following:

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

You may want to implement your own <MultiLanguageCode /> abstraction if you find the above approach too verbose. We might just implement one in future for convenience.

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.