跳转至主内容
Version: 2.0.0-beta.16 🚧

代码块

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

代码标题

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>你好,{props.name}</h1>;
}
```
http://localhost:3000
/src/components/HelloCodeTitle.js
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}

语法高亮

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

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

在代码块中使用相应语言的标签,Docusaurus 将自动使用 Prism React Renderer 为您实现语法高亮。

http://localhost:3000
console.log('Every repo must come with a mascot.');

Theming

我们默认使用的语法高亮主题Palenight。 您可以在 prism 传递 theme 字段,并放入 docusaurus.config.js 中的 themeConfig 来更改主题。

举个例子,如果您喜欢 dracula 高亮主题:

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

Because a Prism theme is just a JS object, you can also write your own theme if you are not satisfied with the default. 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

默认情况下,Docusaurus 自带部分常用语言的支持。

caution

一些如 Java、C# 或 PHP 在内的流行语言默认未启用。

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

For example, if you want to add highlighting for the PowerShell language:

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

After adding additionalLanguages, restart Docusaurus.

如果您想添加 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}`);
});

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

// ...
};

您可在撰写自己的语言定义时参考 Prism 的官方语言定义

行高亮

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 'This text is highlighted!';
}

return 'Nothing highlighted';
}

function HighlightMoreText(highlight) {
if (highlight) {
return 'This range is highlighted!';
}

return 'Nothing highlighted';
}

支持的注释语法: | 语言 | 语法 | | ---------- | ---------------------- | | JavaScript | /* ... */// ... | | JSX | {/* ... */} | | Python | # ... | | HTML | <!-- ... --> | 若有暂不支持的语法,我们很乐意添加! 我们欢迎合并请求。 Docusaurus 以向高亮行添加 docusaurus-highlight-code-line 类的方式来达成此效果。 您需要在 CSS 中定义您自己的样式,其通常位于 src/css/custom.css,而且其中的自定义背景颜色也依赖您所选的语法高亮主题。 下方的颜色适用于默认的语法高亮主题(Palenight)。若您使用其他主题的话,您也需要修改此颜色。

/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);
}

/* 若您在暗色模式中使用了不同的语法高亮主题。 */
html[data-theme='dark'] .docusaurus-highlight-code-line {
/* Color which works with dark mode syntax highlighting theme */
background-color: rgb(100, 100, 100);
}

Highlighting with metadata string

You can also specify highlighted line ranges within the language meta string (leave a space after the language). 要高亮多行内容,请使用半角逗号来分隔行号,或使用范围语法来选择多行代码块。 此功能使用 parse-number-range 库,您可在其项目详情中找到更多语法

```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

Prefer highlighting with comments where you can. By inlining highlight in the code, you don't have to manually count the lines if your code block becomes long. If you add/remove lines, you also don't have to offset your line ranges.

- ```jsx {3}
+ ```jsx {4}
function HighlightSomeText(highlight) {
if (highlight) {
+ console.log('Highlighted text found');
return 'This text is highlighted!';
}

return 'Nothing highlighted';
}
```

In the future, we may extend the magic comment system and let you define custom directives and their functionalities. The magic comments would only be parsed if a highlight metastring is not present.

交互式代码编辑器

(由 React Live 驱动) 您可使用 @docusaurus/theme-live-codeblock 插件创建可交互的代码编辑器。 首先,添加插件至您的网站。

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

您还需要在 docusaurus.config.js 中添加插件。

module.exports = {
// ...
themes: ['@docusaurus/theme-live-codeblock'],
// ...
};

要使用此插件,请先创建代码块,同时在语言源标签中附加上 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 (
<div>
<h2>现在是 {date.toLocaleTimeString()}。</h2>
</div>
);
}
```

此代码块将渲染为可交互的代码编辑器。 代码更改将实时显示在预览区内。

http://localhost:3000
实时编辑器
结果
Loading...

导入

react-live 及导入警告

您无法从 react-live 的代码编辑器中直接导入组件。为此,您需要预先定义可用的导入项。

默认情况下,您可使用 React 的所以导入项。 若您需要更多导入项,您可变换(Swizzle)react-live 的作用域:

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',
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;

现在,您可使用 ButtonExample 组件了:

http://localhost:3000
实时编辑器
结果
Loading...

Using JSX markup in code blocks

Code block in Markdown always preserves its content as plain text, meaning you can't do something like:

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. You have to explicitly write the new line character for it to be printed out.

caution

Syntax highlighting only works on plain strings. Docusaurus will not attempt to parse code block content containing JSX children.

支持多语言的代码块

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

我们并没有实现多语言代码块支持的专用组件,而是在经典主题中编写了通用的选项卡组件,以便您在其他非代码的场景中使用。

下方是在文档中显示多编程语言代码选项卡的示例。 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>

And you will get the following:

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

Displaying CLI commands in both NPM and Yarn is a very common need, for example:

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: {
// ...
},
},
],
],
};

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

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

Using the {sync: true} option would make all tab choices synced. Because the choice is stored under the same namespace npm2yarn, different npm2yarn plugin instances would also sync their choices.

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">
{`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 and title, 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"', 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.