代码块
文档中的代码块功能强大 💪。
代码标题
你可以在语言名称后添加一个 title
键(两者之间留一个空格),为代码块添加标题。
```jsx title="/src/components/HelloCodeTitle.js"
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
```
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
语法高亮
代码块是由三个反引号字符串包裹的文本块。你可以查阅 此参考 以了解 MDX 的规范。
```js
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
高亮主题
import {themes as prismThemes} from 'prism-react-renderer';
export default {
themeConfig: {
prism: {
theme: prismThemes.dracula,
},
},
};
由于 Prism 主题只是一个 JS 对象,如果你不满意默认主题,你也可以编写自己的主题。Docusaurus 增强了 github
和 vsDark
主题以提供更丰富的高亮效果,你可以查看我们对 浅色 和 深色 代码块主题的实现。
支持的语言
默认情况下,Docusaurus 包含 一组常用的语言。
一些流行的语言,如 Java、C# 或 PHP,默认未启用。
要为任何其他 Prism 支持的语言 添加语法高亮,请在附加语言数组中定义它。
每个附加语言都必须是有效的 Prism 组件名称。例如,Prism 会将语言 cs
映射到 csharp
,但只有 prism-csharp.js
作为组件存在,因此你需要使用 additionalLanguages: ['csharp']
。你可以查看 node_modules/prismjs/components
来找到所有可用的组件(语言)。
例如,如果你想为 PowerShell 语言添加高亮
export default {
// ...
themeConfig: {
prism: {
additionalLanguages: ['powershell'],
},
// ...
},
};
添加 additionalLanguages
后,请重启 Docusaurus。
如果你想为 Prism 尚未支持的语言添加高亮,你可以覆盖(swizzle)prism-include-languages
- npm
- Yarn
- pnpm
- Bun
npm run swizzle @docusaurus/theme-classic prism-include-languages
yarn swizzle @docusaurus/theme-classic prism-include-languages
pnpm run swizzle @docusaurus/theme-classic prism-include-languages
bun run swizzle @docusaurus/theme-classic prism-include-languages
它会在你的 src/theme
文件夹中生成 prism-include-languages.js
。你可以通过编辑 prism-include-languages.js
来添加对自定义语言的高亮支持。
const prismIncludeLanguages = (Prism) => {
// ...
additionalLanguages.forEach((lang) => {
require(`prismjs/components/prism-${lang}`);
});
require('/path/to/your/prism-language-definition');
// ...
};
在编写自己的语言定义时,你可以参考 Prism 的官方语言定义。
添加自定义语言定义时,你无需将该语言添加到 additionalLanguages
配置数组中,因为 Docusaurus 只会在 Prism 提供的语言中查找 additionalLanguages
字符串。在 prism-include-languages.js
中添加语言导入就足够了。
行高亮
使用注释高亮
你可以使用带有 highlight-next-line
、highlight-start
和 highlight-end
的注释来选择哪些行被高亮。
```js
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';
}
支持的注释语法
样式 | 语法 |
---|---|
C 风格 | /* ... */ 和 // ... |
JSX 风格 | {/* ... */} |
Bash 风格 | # ... |
HTML 风格 | <!-- ... --> |
我们将尽力根据语言推断要使用哪组注释样式,并默认允许所有注释样式。如果当前不支持某种注释样式,我们乐意添加它们!欢迎提交 Pull Request。请注意,不同的注释样式没有语义上的区别,只有其内容有区别。
你可以在 src/css/custom.css
中设置高亮代码行的背景颜色,使其更好地适应你选择的语法高亮主题。下面给出的颜色适用于默认高亮主题 (Palenight),因此如果你使用其他主题,则需要相应地调整颜色。
: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);
}
如果你还需要以其他方式美化高亮代码行,可以针对 theme-code-block-highlighted-line
CSS 类进行设置。
使用元数据字符串高亮
你还可以在语言元字符串中指定高亮行范围(在语言后留一个空格)。要高亮多行,请用逗号分隔行号,或使用范围语法选择连续的行块。此功能使用 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;
```
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;
尽可能使用注释进行高亮。通过在代码中内联高亮,如果你的代码块很长,你就不必手动计算行数。如果你添加/删除行,你也不必调整行范围的偏移。
- ```jsx {3}
+ ```jsx {4}
function HighlightSomeText(highlight) {
if (highlight) {
+ console.log('Highlighted text found');
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
```
下面,我们将介绍如何扩展魔术注释系统来定义自定义指令及其功能。魔术注释只会在不存在高亮元字符串时才会被解析。
自定义魔术注释
// highlight-next-line
和 // highlight-start
等被称为“魔术注释”,因为它们会被解析并移除,其目的是为下一行或起始-结束注释对所包含的部分添加元数据。
你可以通过主题配置声明自定义魔术注释。例如,你可以注册另一个魔术注释来添加 code-block-error-line
类名
- docusaurus.config.js
- src/css/custom.css
- myDoc.md
export default {
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',
},
],
},
},
};
.code-block-error-line {
background-color: #ff000020;
display: block;
margin: 0 calc(-1 * var(--ifm-pre-padding));
padding: 0 var(--ifm-pre-padding);
border-left: 3px solid #ff000080;
}
In JavaScript, trying to access properties on `null` will error.
```js
const name = null;
// This will error
console.log(name.toUpperCase());
// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase')
```
在 JavaScript 中,尝试访问 null
上的属性将会报错。
const name = null;
console.log(name.toUpperCase());
// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase')
如果你在元字符串中使用数字范围({1,3-4}
语法),Docusaurus 将应用 第一个 magicComments
条目 的类名。默认情况下,这是 theme-code-block-highlighted-line
,但如果你更改 magicComments
配置并使用不同的条目作为第一个,则元字符串范围的含义也会随之改变。
你可以通过设置 magicComments: []
来禁用默认的行高亮注释。如果没有魔术注释配置,但 Docusaurus 遇到包含元字符串范围的代码块,它会报错,因为没有可应用的类名——毕竟,高亮类名只是一个魔术注释条目。
每个魔术注释条目都将包含三个键:className
(必需)、line
(应用于紧邻的下一行),或者 block
(包含 start
和 end
,应用于由两个注释包围的整个块)。
使用 CSS 定位该类已经可以实现很多功能,但你可以通过组件覆盖来充分发挥此功能的潜力。
- npm
- Yarn
- pnpm
- Bun
npm run swizzle @docusaurus/theme-classic CodeBlock/Line
yarn swizzle @docusaurus/theme-classic CodeBlock/Line
pnpm run swizzle @docusaurus/theme-classic CodeBlock/Line
bun run swizzle @docusaurus/theme-classic CodeBlock/Line
Line
组件将接收类名列表,你可以根据这些类名有条件地渲染不同的标记。
行号
你可以在语言元字符串中使用 showLineNumbers
键来启用代码块的行号(不要忘记在键前直接添加空格)。
```jsx showLineNumbers
import React from 'react';
export default function MyComponent(props) {
return <div>Foo</div>;
}
```
import React from 'react';
export default function MyComponent(props) {
return <div>Foo</div>;
}
默认情况下,计数器从行号 1 开始。可以传递自定义的计数器起始值,以便分割大型代码块以提高可读性。
```jsx showLineNumbers=3
export default function MyComponent(props) {
return <div>Foo</div>;
}
```
export default function MyComponent(props) {
return <div>Foo</div>;
}
交互式代码编辑器
(由 React Live 提供支持)
你可以使用 @docusaurus/theme-live-codeblock
插件创建一个交互式代码编辑器。首先,将该插件添加到你的包中。
- npm
- Yarn
- pnpm
- Bun
npm install --save @docusaurus/theme-live-codeblock
yarn add @docusaurus/theme-live-codeblock
pnpm add @docusaurus/theme-live-codeblock
bun add @docusaurus/theme-live-codeblock
你还需要将该插件添加到你的 docusaurus.config.js
中。
export default {
// ...
themes: ['@docusaurus/theme-live-codeblock'],
// ...
};
要使用该插件,请创建一个代码块,并在语言元字符串中附加 live
。
```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>
);
}
```
代码块将渲染为交互式编辑器。代码的更改将实时反映在结果面板上。
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> ); }
导入
无法直接从 react-live 代码编辑器导入组件,你必须预先定义可用的导入。
默认情况下,所有 React 导入都可用。如果你需要更多可用的导入,请覆盖(swizzle)react-live 作用域
- npm
- Yarn
- pnpm
- Bun
npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope -- --eject
yarn swizzle @docusaurus/theme-live-codeblock ReactLiveScope --eject
pnpm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope --eject
bun run swizzle @docusaurus/theme-live-codeblock ReactLiveScope --eject
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
组件现在可以使用了
function MyPlayground(props) { return ( <div> <ButtonExample onClick={() => alert('hey!')}>Click me</ButtonExample> </div> ); }
命令式渲染 (noInline)
当你的代码跨越多个组件或变量时,应使用 noInline
选项以避免错误。
```jsx live noInline
const project = 'Docusaurus';
const Greeting = () => <p>Hello {project}!</p>;
render(<Greeting />);
```
与普通交互式代码块不同,当使用 noInline
时,React Live 不会将你的代码包裹在内联函数中进行渲染。
你需要在代码末尾明确调用 render()
来显示输出。
const project = "Docusaurus"; const Greeting = () => ( <p>Hello {project}!</p> ); render( <Greeting /> );
在代码块中使用 JSX 标记
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;
如果你想嵌入 HTML 标记,如锚链接或粗体文本,你可以使用 <pre>
标签、<code>
标签或 <CodeBlock>
组件。
<pre>
<b>Input: </b>1 2 3 4{'\n'}
<b>Output: </b>"366300745"{'\n'}
</pre>
Input: 1 2 3 4 Output: "366300745"
MDX 与 JSX 行为一致:换行符,即使在 <pre>
内部,也会转换为空格。你必须显式地编写换行符才能将其打印出来。
语法高亮仅适用于纯字符串。Docusaurus 不会尝试解析包含 JSX 子项的代码块内容。
多语言支持代码块
借助 MDX,你可以在文档中轻松创建交互式组件,例如,使用选项卡组件显示多种编程语言的代码并在它们之间切换。
我们没有为多语言支持代码块实现专用组件,而是在经典主题中实现了一个通用型 <Tabs>
组件,这样你也可以将其用于其他非代码场景。
以下是如何在你的文档中拥有多语言代码选项卡的示例。请注意,每个语言块上方和下方的空行是有意为之的。这是 MDX 的当前限制:你必须在 Markdown 语法周围留空行,以便 MDX 解析器知道它是 Markdown 语法而不是 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>
你将得到以下内容
- JavaScript
- Python
- Java
function helloWorld() {
console.log('Hello, world!');
}
def hello_world():
print("Hello, world!")
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
如果你有多个这样的多语言代码选项卡,并且希望在选项卡实例之间同步选择,请参阅同步选项卡选择部分。
Docusaurus npm2yarn remark 插件
在 npm 和 Yarn 中显示 CLI 命令是一种非常常见的需求,例如
- npm
- Yarn
- pnpm
- Bun
npm install @docusaurus/remark-plugin-npm2yarn
yarn add @docusaurus/remark-plugin-npm2yarn
pnpm add @docusaurus/remark-plugin-npm2yarn
bun add @docusaurus/remark-plugin-npm2yarn
Docusaurus 开箱即用地提供了这样的实用工具,让你无需每次都使用 Tabs
组件。要启用此功能,首先按照上述方式安装 @docusaurus/remark-plugin-npm2yarn
包,然后在 docusaurus.config.js
中,对于需要此功能的插件(文档、博客、页面等),将其注册到 remarkPlugins
选项中。(有关配置格式的更多详细信息,请参阅文档配置)
export default {
// ...
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']},
],
],
// ...
},
},
],
],
};
然后通过向代码块添加 npm2yarn
键来使用它
```bash npm2yarn
npm install @docusaurus/remark-plugin-npm2yarn
```
配置
选项 | 类型 | 默认值 | 描述 |
---|---|---|---|
同步 | 布尔值 | false | 是否在所有代码块之间同步选定的转换器。 |
转换器 | 数组 | 'yarn' , 'pnpm' | 要使用的转换器列表。转换器的顺序很重要,因为第一个转换器将用作默认选择。 |
在 JSX 中使用
在 Markdown 之外,你可以使用 @theme/CodeBlock
组件获得相同的输出。
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>
);
}
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
接受的 props 包括 language
、title
和 showLineNumbers
,与你编写 Markdown 代码块的方式相同。
尽管不推荐,你也可以传入 metastring
prop,例如 metastring='{1-2} title="/src/components/HelloCodeTitle.js" showLineNumbers'
,这是 Markdown 代码块在底层处理的方式。但是,我们建议你使用注释进行行高亮。
如前所述,语法高亮仅在子元素是简单字符串时才适用。