代码块

以 Markdown 格式查看

<CodeBlock> 组件用于显示带语法高亮的代码示例。代码块支持行高亮、聚焦、标题和深度链接,让您的代码示例更易读、更具交互性。

用法

使用三个反引号,并可选地添加语言标识符。

1console.log("hello world")
Markdown
1```js
2console.log("hello world")
3```
支持的语言

Fern 通过 Shiki 为以下语言提供语法高亮支持:

  • javascript (别名:jsnode
  • python
  • java
  • typescript (别名:ts
  • csharp
  • cpp
  • c
  • php
  • go
  • rust
  • ruby
  • swift
  • kotlin
  • sql
  • bash (别名:shellsh
  • curl
  • markdown (别名:md
  • http

如果您指定了不在该列表中的语言,Fern 仍会显示代码块,但不会进行语法高亮。

变体

标题

在语言标识符之后添加标题,即可为代码片段添加标题。或者使用 title 属性(title="带标题的片段")或 filename 属性(filename="带标题的片段")实现相同效果。

带标题的片段
1console.log("hello world")
Markdown
1```js 带标题的片段
2console.log("hello world")
3```

行高亮

通过在语言标识符后的 {} 中放入数字范围,可以高亮代码片段中的特定行。范围为闭区间,可以是单个数字、用逗号分隔的多个数字,或区间。

1console.log("Line 1");
2console.log("Line 2");
3console.log("Line 3");
4console.log("Line 4");
5console.log("Line 5");
6console.log("Line 6");
Markdown
1```javascript {2-4, 6}
2console.log("Line 1");
3console.log("Line 2");
4console.log("Line 3");
5console.log("Line 4");
6console.log("Line 5");
7console.log("Line 6");
8```

行聚焦

通过添加注释 [!code focus],或在语言标识符后添加 focus 属性,可聚焦特定行。

1console.log("Line 1");
2console.log("Line 2");
3console.log("Line 3");
4console.log("Line 4");
5console.log("Line 5");
Markdown
1```javascript focus={2-4}
2console.log("Line 1");
3console.log("Line 2");
4console.log("Line 3");
5console.log("Line 4");
6console.log("Line 5");
7```

起始行号

通过在语言标识符后添加 startLine 属性,可控制代码块中显示的第一行行号。这对较长的代码片段非常有用——既能突出主要逻辑,又能保留完整上下文。

1 console.log("Line 1");
2 console.log("Line 2");
3 console.log("Line 3");
4 console.log("Line 4");
5 console.log("Line 5");
6 console.log("Line 6");
7 console.log("Line 7");
8 console.log("Line 8");
9 console.log("Line 9");
10 console.log("Line 10");
11 console.log("Line 11");
12 console.log("Line 12");
13 console.log("Line 13");
14 console.log("Line 14");
15 console.log("Line 15");
16 console.log("Line 16");
17 console.log("Line 17");
18 console.log("Line 18");
19 console.log("Line 19");
20 console.log("Line 20");
21 console.log("Line 21");
22 console.log("Line 22");
23 console.log("Line 23");
24 console.log("Line 24");
25 console.log("Line 25");
26 console.log("Line 26");
27 console.log("Line 27");
28 console.log("Line 28")
Markdown
1```javascript startLine={6}
2console.log("Line 1");
3console.log("Line 2");
4console.log("Line 3");
5console.log("Line 4");
6console.log("Line 5");
7console.log("Line 6");
8console.log("Line 7");
9console.log("Line 8");
10console.log("Line 9");
11console.log("Line 10");
12console.log("Line 11");
13console.log("Line 12");
14console.log("Line 13");
15console.log("Line 14");
16console.log("Line 15");
17console.log("Line 16");
18console.log("Line 17");
19console.log("Line 18");
20console.log("Line 19");
21console.log("Line 20");
22console.log("Line 21");
23console.log("Line 22");
24console.log("Line 23");
25console.log("Line 24");
26console.log("Line 25");
27console.log("Line 26");
28console.log("Line 27");
29console.log("Line 28")
30```

最大高度

在语言标识符后添加 maxLines 属性可控制代码块的最大高度。maxLines 应为表示最大显示行数的数字。默认情况下,代码块最多显示 20 行。(如需禁用默认 20 行限制,请将 maxLines 设为 0。)

当您使用 maxLines 时,鼠标悬停时右上角会自动出现展开按钮,用户点击后可在覆盖在页面上的展开层中查看完整代码内容。

1def is_prime(num):
2 """Check if a number is prime."""
3 if num <= 1:
4 return False
5 for i in range(2, num):
6 if num % i == 0:
7 return False
8 return True
9
10start = 10
11end = 50
12
13print(f"Prime numbers between {start} and {end} are:")
14
15prime_numbers = []
16
17for num in range(start, end+1):
18 if is_prime(num):
19 prime_numbers.append(num)
20
21for prime in prime_numbers:
22 print(prime)
Markdown
1```python maxLines=10
2def is_prime(num):
3 """Check if a number is prime."""
4 if num <= 1:
5 return False
6 for i in range(2, num):
7 if num % i == 0:
8 return False
9 return True
10
11start = 10
12end = 50
13
14print(f"Prime numbers between {start} and {end} are:")
15
16prime_numbers = []
17
18for num in range(start, end+1):
19 if is_prime(num):
20 prime_numbers.append(num)
21
22for prime in prime_numbers:
23 print(prime)
24```
自定义样式

如需隐藏展开按钮或添加自定义样式,请针对 .fern-expand-button 选择器进行设置:

1/* 隐藏展开按钮 */
2.fern-expand-button {
3 display: none;
4}

换行处理

默认情况下,超出代码块宽度的长行会变为可滚动:

Without wordWrap
A very very very long line of text that may cause the code block to overflow and scroll as a result.
Markdown
1```txt title="Without wordWrap"
2A very very very long line of text that may cause the code block to overflow and scroll as a result.
3```

要禁用滚动并将超出部分换到下一行,请使用 wordWrap 属性:

With wordWrap
A very very very long line of text that may cause the code block to overflow and scroll as a result.
Markdown
1```txt title="With wordWrap" wordWrap
2A very very very long line of text that may cause the code block to overflow and scroll as a result.
3```

隐藏行号

默认情况下,代码块会在边栏显示行号(在 bash/shell 代码块中还会显示 $ / > 前缀)。要隐藏行号和前缀,请将 showLineNumbers 设置为 false

npm install plantstore
npm run build \
--output dist
Markdown
1```bash showLineNumbers={false}
2npm install plantstore
3npm run build \
4 --output dist
5```

深度链接

通过定义 links 映射,可让代码块中的特定文本变为可点击。这对从代码示例直接链接到文档、API 参考或相关资源非常有用。

links 属性接受一个映射,其中键为匹配模式(精确字符串或正则表达式),值为目标 URL。

1import { PlantClient } from "@plantstore/sdk";
2
3const client = new PlantClient({ apiKey: "YOUR_API_KEY" });
4const plant = await client.createPlant({
5 name: "Monstera",
6 species: "Monstera deliciosa"
7});
Markdown
1<CodeBlock
2 links={{"PlantClient": "/learn/docs/writing-content/demo#plantclient", "createPlant": "/learn/docs/writing-content/demo#create_plant"}}
3>
4```typescript
5import { PlantClient } from "@plantstore/sdk";
6
7const client = new PlantClient({ apiKey: "YOUR_API_KEY" });
8const plant = await client.createPlant({
9 name: "Monstera",
10 species: "Monstera deliciosa"
11});
12```
13</CodeBlock>

links 属性使用 JSON 格式。映射中的每个键会与代码块中的文本进行精确匹配,匹配到的文本将变为指向对应 URL 的可点击链接。

您可以使用正则表达式实现更灵活的匹配。当您想要匹配多种文本变体或模式时,这非常有用。

在下面的示例中,/get\\w+/ 会同时匹配 getPlantgetGarden,而 /Plant(Store|Client)/ 会同时匹配 PlantStorePlantClient

1from plantstore import PlantStore, PlantClientfrom plantstore import PlantStore, PlantClient
2
3store = PlantStore(api_key="YOUR_API_KEY")
4client = PlantClient(store)
5
6plant = store.getPlant(plant_id="123")
7garden = store.getGarden(garden_id="456")
Markdown
1<CodeBlock
2 links={{"/get\\w+/": "/learn/docs/writing-content/demo#get-methods", "/Plant(Store|Client)/": "/learn/docs/writing-content/demo#type-definitions"}}
3>
4```python
5from plantstore import PlantStore, PlantClient
6
7store = PlantStore(api_key="YOUR_API_KEY")
8client = PlantClient(store)
9
10plant = store.getPlant(plant_id="123")
11garden = store.getGarden(garden_id="456")
12```
13</CodeBlock>

使用正则表达式时,请记得在 JSON 字符串中用双反斜杠转义特殊字符(例如 \\w+\\d+)。

嵌入代码文件

通过在 <Code> 组件上使用 src 属性,可以嵌入本地或外部文件中的代码。对于本地文件,请使用相对于 docs 目录的路径;对于外部文件,请使用完整 URL,从 GitHub 等远程源直接拉取代码示例。

<Code> 组件支持与 <CodeBlock> 相同的所有属性,包括 titlelanguagemaxLines

Local file
1console.log("I love Fern!");
example-code.js
1console.log("I also love Fern!");
Markdown
1```js
2
3console.log("I love Fern!");
4
5```
6<Code src="snippets/example-code.js">
GitHub Actions 工作流(外部文件)
1name: fern-check
2
3on:
4 pull_request:
5 push:
6 branches:
7 - main
8
9jobs:
10 run:
11 runs-on: ubuntu-latest
12 steps:
13 - name: Checkout repository
14 uses: actions/checkout@v4
15
16 - name: Setup Fern CLI
17 uses: fern-api/setup-fern-cli@v1
18
19 - name: Check API is valid
20 run: fern check
Markdown
1<Code
2 src="https://raw.githubusercontent.com/fern-api/docs-starter/refs/heads/main/.github/workflows/check.yml"
3 title="GitHub Actions workflow"
4 language="yaml"
5 maxLines={15}
6>

带标签页的代码块

在标签页界面中显示多个代码块。

1puts "Hello World"
Markdown
1<CodeBlocks>
2 ```ruby title="hello_world.rb"
3 puts "Hello World"
4 ```
5
6 ```php title="hello_world.php"
7 <?php
8 echo "Hello World";
9 ?>
10 ```
11
12 ```rust title="hello_world.rs"
13 fn main() {
14 println!("Hello World");
15 }
16 ```
17</CodeBlocks>

语言同步

设置了相同语言的代码块会在整个文档站点中自动同步。当用户选择某种语言时,所有该语言的代码块都会同步切换。语言偏好会跨浏览器会话保留。

1print("First code block!")
1print("Second code block - syncs with the one above!")

代码块会自动与相同语言的标签页同步。

您可以通过在 URL 末尾添加 ?language=<某种语言> 来直接链接到特定语言的内容。这将设置用户访问页面时默认显示的语言标签。

例如,以下链接会默认显示 Java 标签页:https://buildwithfern.com/learn/docs/writing-content/components/tabs?language=java

这适用于具有 language 属性的 CodeBlocksTab 组件。

使用 for 属性可以创建独立于语言的自定义同步分组。这对于按其他维度分组代码块(例如按包管理器或框架)非常有用。

$npm install plantstore
$npm uninstall plantstore
Markdown
1<CodeGroup>
2 ```bash title="使用 npm 安装" for="npm"
3 npm install plantstore
4 ```
5 ```bash title="使用 pnpm 安装" for="pnpm"
6 pnpm add plantstore
7 ```
8 ```bash title="使用 yarn 安装" for="yarn"
9 yarn add plantstore
10 ```
11</CodeGroup>
12
13<CodeGroup>
14 ```bash title="使用 npm 卸载" for="npm"
15 npm uninstall plantstore
16 ```
17 ```bash title="使用 pnpm 卸载" for="pnpm"
18 pnpm remove plantstore
19 ```
20 ```bash title="使用 yarn 卸载" for="yarn"
21 yarn remove plantstore
22 ```
23</CodeGroup>

属性

代码块属性

这些属性可以在 markdown 代码块的语言标识符后添加,也可以作为 <CodeBlock> 组件的 props 使用。

language
string

用于语法高亮的编程语言。支持的语言:javascript(别名:jsnode)、pythonjavatypescript(别名:ts)、csharpcppcphpgorustrubyswiftkotlinsqlbash(别名:shellsh)、curlmarkdown(别名:md)、http

title
string

显示在代码块上方的标题。可以在语言标识符后内联指定,或通过 title="..."filename="..." 属性指定。

highlight
string

要高亮的行,使用 {2-4, 6} 语法指定。支持单个数字、范围和逗号分隔的列表。

focus
string

要聚焦的行,使用 focus={2-4} 指定。用法与 highlight 相同,但会将未聚焦的行变暗。

startLine
number

开始显示的行号。在显示较长代码文件的特定部分时非常有用。

maxLines
numberDefaults to 20

开始添加滚动前显示的最大行数。设置为 0 可禁用此限制。

wordWrap
booleanDefaults to false

是否对长行进行换行处理(而非滚动显示)。

showLineNumbers
booleanDefaults to true

是否在边栏显示行号,包括 bash/shell 代码块中的命令提示符($>)。设置为 false 可隐藏行号,让代码示例外观更简洁。

for
string

自定义同步分组标识符。会覆盖默认的基于语言的同步行为。

links
object

文本模式到 URL 的映射,用于在代码内创建可点击链接。键可以是精确字符串或正则表达式(例如 {"/get\\w+/": "/api-docs"})。

<Code> 属性

<Code> 组件用于嵌入文件中的代码。它接受上面列出的所有代码块属性,外加:

src
stringRequired

本地文件路径(相对于 docs 目录)或外部文件的完整 URL(例如 GitHub raw URL)。

lines
number[]

从源文件中提取的行号。支持单行([5])、范围([2-4])和组合形式([1-3,5,7-10])。行号从 1 开始。