关于 orval
orval 根据 OpenAPI v3 和 Swagger v2 规范生成类型安全的 TypeScript 客户端及相关代码,适用于 API 开发团队。它支持多种前端数据查询客户端、校验模式和服务端处理器。
主要功能
- 01生成类型安全的 TypeScript 客户端
- 02生成查询钩子、模式和模拟数据
- 03支持多种前端客户端与 HTTP 库
- 04按标签或文件拆分输出
- 05从多个 API 规范生成代码
适用场景
- 01为前端项目生成 API 调用代码
- 02生成 Zod 运行时校验模式
- 03为 Hono API 生成服务端处理器
MCP 相关
orval 可从 OpenAPI 规范生成 MCP 服务,供 AI Agent 使用生成的 API 工具。
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ orval-labs/ orval --skill orval安装后在 Claude Code 中输入/orval确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
advanced-config.mdangular.mdcustom-http-clients.mdhono.mdmocking-msw.mdsolid-start.mdtanstack-query.mdtooling-workflow.mdzod-validation.md详细介绍
Orval - OpenAPI 转 TypeScript 代码生成器
Orval 可根据 OpenAPI v3/Swagger v2 规范生成类型安全的 TypeScript 客户端、钩子、架构、模拟对象和服务端处理程序。
快速开始
安装
npm install orval -D
# or yarn add orval -D
# or pnpm add orval -D
# or bun add orval -D
最小配置
import { defineConfig } from 'orval';
export default defineConfig({
petstore: {
input: {
target: './petstore.yaml',
},
output: {
target: './src/api/petstore.ts',
schemas: './src/api/model',
client: 'react-query',
},
},
});
运行
npx orval
npx orval --config ./orval.config.ts
npx orval --project petstore
npx orval --watch
选择设置
客户端选择指南
| 用例 | 客户端 | httpClient | 说明 |
|---|---|---|---|
| 使用服务端状态的 React | react-query | fetch 或 axios | TanStack Query 钩子 |
| 使用服务端状态的 Vue 3 | vue-query | fetch 或 axios | 用于 Vue 的 TanStack Query |
| 使用服务端状态的 Svelte | svelte-query | fetch 或 axios | 用于 Svelte 的 TanStack Query |
| 独立的 SolidJS 应用 | solid-query | fetch 或 axios | 用于 Solid 的 TanStack Query |
| 全栈 SolidStart | solid-start | 原生 fetch | 使用 query()/action() 原语 |
| 使用 signals 的 Angular | angular-query | angular | 可注入函数,响应式 signals |
| 传统 Angular | angular | — | HttpClient 服务 |
| 使用 SWR 的 React | swr | fetch 或 axios | Vercel SWR 钩子 |
| 轻量 / Edge | fetch | — | 零依赖,随处可用 |
| Node.js / 现有 Axios | axios-functions | — | 工厂函数(默认) |
| 使用 DI 的 Axios | axios | — | 可注入的 Axios 实例 |
| 仅验证 | zod | — | Zod 架构,无 HTTP 客户端 |
| 后端 API 服务端 | hono | — | 使用 Zod 验证的 Hono 处理程序 |
| AI Agent 工具 | mcp | — | Model Context Protocol 服务 |
模式选择指南
single— 所有内容放在一个文件中。最适合小型 API。split— 拆分为多个文件:petstore.ts、petstore.schemas.ts、petstore.msw.ts。适用于中型 API。tags— 每个 OpenAPI 标签对应一个文件,另有共享架构。按领域组织。tags-split— 每个标签对应一个文件夹,文件拆分存放。最适合大型 API。推荐使用。
httpClient 选项
对于 react-query、vue-query、svelte-query 和 swr 客户端:
output: {
client: 'react-query',
httpClient: 'fetch', // 'fetch' (default) | 'axios'
}
对于 angular-query:
output: {
client: 'angular-query',
httpClient: 'angular', // Uses Angular HttpClient
}
配置参考
配置结构
import { defineConfig } from 'orval';
export default defineConfig({
[projectName]: {
input: InputOptions,
output: OutputOptions,
hooks: HooksOptions,
},
});
多个项目可以使用同一个配置文件,并设置不同的输入/输出选项。
输入选项
input: {
target: './spec.yaml', // Path or URL to OpenAPI spec (required)
override: {
transformer: './transform.js', // Transform spec before generation
},
filters: {
mode: 'include', // 'include' | 'exclude'
tags: ['pets', /health/], // Filter by OpenAPI tags
schemas: ['Pet', /Error/], // Filter by schema names
},
parserOptions: {
headers: [ // Auth headers for remote spec URLs
{
domains: ['api.example.com'],
headers: {
Authorization: 'Bearer YOUR_TOKEN',
'X-API-Key': 'your-api-key',
},
},
],
},
}
输出选项
output: {
target: './src/api/endpoints.ts', // Output path (required)
client: 'react-query', // Client type (see table above)
httpClient: 'fetch', // 'fetch' (default) | 'axios' | 'angular'
mode: 'tags-split', // 'single' | 'split' | 'tags' | 'tags-split'
schemas: './src/api/model', // Output path for model types
operationSchemas: './src/api/params', // Separate path for operation-derived types
workspace: 'src/', // Base folder for all files
fileExtension: '.ts', // Custom file extension
namingConvention: 'camelCase', // File naming: camelCase | PascalCase | snake_case | kebab-case
indexFiles: true, // Generate index.ts barrel files
clean: true, // Clean output before generating
prettier: true, // Format with Prettier
biome: true, // Format with Biome
headers: true, // Generate header parameters
baseUrl: '/api/v2', // API base URL
// or from spec:
// baseUrl: { getBaseUrlFromSpecification: true, index: 0, variables: { environment: 'api.dev' } },
mocks: true, // Generate MSW + Faker mocks (boolean, object, or function)
docs: true, // Generate TypeDoc documentation
// docs: { configPath: './typedoc.config.mjs' },
allParamsOptional: true, // Make all params optional (except path params)
urlEncodeParameters: true, // URL-encode path/query parameters
optionsParamRequired: false, // Make options parameter required
propertySortOrder: 'Specification', // 'Alphabetical' | 'Specification'
tsconfig: './tsconfig.json', // Custom tsconfig path
override: { ... }, // Advanced overrides (see below)
}
多个 API 规范
export default defineConfig({
petstoreV1: {
input: { target: './specs/v1.yaml' },
output: { target: 'src/api/v1', client: 'react-query' },
},
petstoreV2: {
input: { target: './specs/v2.yaml' },
output: { target: 'src/api/v2', client: 'react-query' },
},
});
筛选端点
input: {
target: './spec.yaml',
filters: {
mode: 'include',
tags: ['pets'],
},
}
详细指南
当用户的问题涉及以下特定主题时,请从此技能的目录中读取对应文件。
| 主题 | 文件 | 在用户询问以下内容时加载 |
|---|---|---|
| TanStack Query / SWR | tanstack-query.md | React Query、Vue Query、Svelte Query、Solid Query、SWR、查询钩子、失效处理、无限查询、Suspense、预取 |
| Angular | angular.md | Angular Query、Angular HttpClient、signals、inject 函数、Angular 服务、providedIn |
| SolidStart | solid-start.md | SolidStart、@solidjs/router、query()、action()、createAsync、revalidate |
| 自定义 HTTP / Auth | custom-http-clients.md | 自定义 mutator、身份验证、令牌、拦截器、自定义 fetch/axios、baseURL、基于钩子的 mutator |
| Zod 验证 | zod-validation.md | Zod schemas、验证、运行时验证、coerce、strict、preprocess |
| Mock / MSW | mocking-msw.md | MSW mocks、测试、测试设置、faker、Vitest、mock handlers、useExamples |
| Hono 服务 | hono.md | Hono handlers、zValidator、组合路由、上下文类型、服务端生成 |
| 高级配置 | advanced-config.md | 类型生成、枚举、按操作覆盖、FormData、JSDoc、参数序列化器、完整示例 |
| 工具 / 工作流 | tooling-workflow.md | 编程式 API、转换器、钩子、NDJSON 流式传输、MCP、afterAllFilesWrite |
OpenAPI 规范最佳实践
- 为每个操作使用唯一的
operationId— Orval 使用这些 ID 命名函数和钩子 - 在
components/schemas中定义可复用的 schemas — 减少生成类型中的重复内容 - 使用 tags 对操作分组 — 适用于
tags和tags-split模式 - 为所有操作定义响应类型 — 实现完整的类型安全
- 标记必填字段 — 影响生成的 TypeScript 接口中字段是否可选
- 对数字枚举使用
x-enumNames— 生成易读的 const 名称 - 提供
example值 — 在useExamples: true时用于生成 mock - 对流式端点使用
application/x-ndjson内容类型 — 支持生成带类型的 NDJSON
CLI 参考
orval # Generate using auto-discovered config
orval --config ./api/orval.config.ts # Specify config file
orval --project petstore # Run specific project(s)
orval --watch # Watch mode
orval --watch ./src # Watch specific directory
orval --clean # Clean generated files
orval --prettier # Format with Prettier
orval --biome # Format with Biome
orval --tsconfig ./src/tsconfig.json # Custom tsconfig path
orval --mode split # Override output mode
orval --client react-query # Override client
orval --mock # Override mock generation
orval --input ./spec.yaml --output ./api.ts # Direct generation
资源
评论
支持 Markdown