> For AI agents: the complete documentation index is available at https://rspress.rs/zh/llms.txt, the full documentation bundle is available at https://rspress.rs/zh/llms-full.txt.

# @rspress/plugin-twoslash 

[源码](https://github.com/web-infra-dev/rspress/tree/main/packages/plugin-twoslash)

集成 [Twoslash](https://github.com/twoslashes/twoslash) 的 Rspress 插件，用于自动生成带有类型信息的丰富代码块。

## 安装


```sh [npm]
npm add @rspress/plugin-twoslash -D
```

```sh [yarn]
yarn add @rspress/plugin-twoslash -D
```

```sh [pnpm]
pnpm add @rspress/plugin-twoslash -D
```

```sh [bun]
bun add @rspress/plugin-twoslash -D
```

```sh [deno]
deno add npm:@rspress/plugin-twoslash -D
```

## 使用

### 1. 注册插件

```ts twoslash title="rspress.config.ts"
import { defineConfig } from '@rspress/core';
import { pluginTwoslash } from '@rspress/plugin-twoslash';

export default defineConfig({
  plugins: [pluginTwoslash()],
});
```

### 2. 使用 Twoslash 编写代码块

在 TypeScript 代码块中使用特殊注释来启用 Twoslash 功能。

更详细的用法，请参考 [Twoslash 文档](https://twoslash.netlify.app/guide/)。

#### 提取类型


**结果**

```ts twoslash
const hi = 'Hello';
const msg = `${hi}, world`;
//    ^?
```


**语法**

````mdx
```ts twoslash
const hi = 'Hello';
const msg = `${hi}, world`;
//    ^?
```
````


#### 自动补全


**结果**

```ts twoslash
// @noErrors
console.e;
//       ^|
```


**语法**

````mdx
```ts twoslash
// @noErrors
console.e;
//       ^|
```
````


#### 高亮显示


**结果**

```ts twoslash
function add(a: number, b: number) {
  //     ^^^
  return a + b;
}
```


**语法**

````mdx
```ts twoslash
function add(a: number, b: number) {
  //     ^^^
  return a + b;
}
```
````


#### 错误提示


**结果**

```ts twoslash
// @noErrorValidation
const str: string = 1;
```


**语法**

````mdx
```ts twoslash
// @noErrorValidation
const str: string = 1;
```
````


## 配置

该插件接受一个对象,具有以下类型：

```ts twoslash
import { TwoslashOptions } from 'twoslash';
// ---cut-before---
export interface PluginTwoslashOptions {
  explicitTrigger?: boolean;
  cache?: boolean;
  twoslashOptions?: TwoslashOptions;
}
```

### explicitTrigger

`explicitTrigger` 用于配置是否显式触发 twoslash 功能。默认值为 `true`。

- 如果设置为 `false`，默认情况下所有 TypeScript 代码块都将被处理。
- 如果设置为 `true`，只有带有 `twoslash` 标签的代码块才会被处理。

### cache

`cache` 用于在 [createTwoslasher](https://twoslash.netlify.app/refs/api#createtwoslasher) 时根据编译器选项缓存 TypeScript 语言服务器。默认值为 `true`。

### twoslashOptions

`twoslashOptions` 用于传递选项到 Twoslash。
这允许您自定义 Twoslash 的行为,包括 TypeScript 编译器选项和其他设置。
