# 类型替换器 (/docs/plugin-system/builtin-plugins/import-type)



# 类型替换器 [#类型替换器]

本插件用于将外部类型注入到生成的代码中，避免 worma 自动重复生成这些类型。

## 主要功能 [#主要功能]

* 引入自定义类型，替换自动生成
* 支持 `import type` 语法（通过 `|type` 后缀标记）
* 支持指定目标文件（默认 `globals.d`）
* 内部使用 `beforeCodeGenerate` + `beforeFileWrite` 实现，兼容流式渲染

## 基本使用 [#基本使用]

```javascript
import { defineConfig } from 'wormajs';
import { importType } from 'wormajs/plugin';

export default defineConfig({
  generator: [
    {
      plugins: [
        importType(
          {
            'my-types|type': ['Pagination', 'BaseResponse'],  // import type
            '@/shared': ['File', 'FormData'],                 // import
          },
          { files: ['globals.d', 'types'] }                   // 目标文件
        ),
      ],
    },
  ],
});
```

以上配置将生成：

```typescript
import type { Pagination, BaseResponse } from "my-types";
import { File, FormData } from "@/shared";
```

并将 `Pagination`、`BaseResponse`、`File`、`FormData` 排除在自动生成之外。

## 配置参数 [#配置参数]

```typescript
function importType(
  imports: Record<string, string[]>,
  options?: { files?: string[] }
): ApiPlugin;
```

### 参数说明 [#参数说明]

* `imports`：模块路径到类型名称的映射
  * key 包含 `|type` 后缀时（如 `'module-name|type'`），生成 `import type { ... }` 语句
  * 否则生成普通 `import { ... }` 语句
* `options.files`：目标文件名匹配列表，默认为 `['globals.d']`

### 多模块配置 [#多模块配置]

```javascript
importType({
  'my-types|type': ['Pagination', 'BaseResponse'],
  '@/shared': ['File', 'FormData'],
  'vue|type': ['Vue'],
});
```

生成结果：

```typescript
import type { Pagination, BaseResponse } from "my-types";
import { File, FormData } from "@/shared";
import type { Vue } from "vue";
```

### 自定义目标文件 [#自定义目标文件]

默认注入到 `globals.d` 文件，也可以通过 `files` 参数指定其他文件：

```javascript
importType(
  { 'my-types|type': ['Pagination'] },
  { files: ['globals.d', 'types', 'index'] }
);
```
