orval
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOrval - OpenAPI to TypeScript Code Generator
Orval - OpenAPI转TypeScript代码生成器
Orval generates type-safe TypeScript clients, hooks, schemas, mocks, and server handlers from OpenAPI v3/Swagger v2 specifications.
Orval 可从 OpenAPI v3/Swagger v2 规范生成类型安全的 TypeScript 客户端、钩子、模式、模拟以及服务器处理器。
Quick Start
快速开始
Installation
安装
bash
npm install orval -Dbash
npm install orval -Dor yarn add orval -D
or yarn add orval -D
or pnpm add orval -D
or pnpm add orval -D
or bun add orval -D
or bun add orval -D
undefinedundefinedMinimal Configuration
最简配置
ts
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',
},
},
});ts
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',
},
},
});Run
运行
bash
npx orval
npx orval --config ./orval.config.ts
npx orval --project petstore
npx orval --watchbash
npx orval
npx orval --config ./orval.config.ts
npx orval --project petstore
npx orval --watchChoosing Your Setup
选择你的配置方案
Client Selection Guide
客户端选择指南
| Use Case | Client | httpClient | Notes |
|---|---|---|---|
| React with server state | | | TanStack Query hooks |
| Vue 3 with server state | | | TanStack Query for Vue |
| Svelte with server state | | | TanStack Query for Svelte |
| SolidJS standalone app | | | TanStack Query for Solid |
| SolidStart full-stack | | native fetch | Uses |
| Angular with signals | | | Injectable functions, signal reactivity |
| Angular traditional | | — | HttpClient services |
| React with SWR | | | Vercel SWR hooks |
| Lightweight / Edge | | — | Zero dependencies, works everywhere |
| Node.js / existing Axios | | — | Factory functions (default) |
| Axios with DI | | — | Injectable Axios instance |
| Validation only | | — | Zod schemas, no HTTP client |
| Backend API server | | — | Hono handlers with Zod validation |
| AI agent tools | | — | Model Context Protocol servers |
| 使用场景 | 客户端 | httpClient | 说明 |
|---|---|---|---|
| React 服务端状态管理 | | | TanStack Query 钩子 |
| Vue 3 服务端状态管理 | | | Vue 版 TanStack Query |
| Svelte 服务端状态管理 | | | Svelte 版 TanStack Query |
| SolidJS 独立应用 | | | Solid 版 TanStack Query |
| SolidStart 全栈应用 | | 原生 fetch | 使用 |
| Angular 信号式状态管理 | | | 可注入函数、信号响应式 |
| 传统 Angular 应用 | | — | HttpClient 服务 |
| React 搭配 SWR | | | Vercel SWR 钩子 |
| 轻量/边缘环境 | | — | 零依赖,支持所有环境 |
| Node.js / 已有 Axios 环境 | | — | 工厂函数(默认) |
| 依赖注入式 Axios | | — | 可注入的 Axios 实例 |
| 仅需验证 | | — | Zod 模式,无 HTTP 客户端 |
| 后端 API 服务器 | | — | 带 Zod 验证的 Hono 处理器 |
| AI Agent 工具 | | — | 模型上下文协议(Model Context Protocol)服务器 |
Mode Selection Guide
模式选择指南
- — Everything in one file. Best for small APIs.
single - — Separate files:
split,petstore.ts,petstore.schemas.ts. Good for medium APIs.petstore.msw.ts - — One file per OpenAPI tag + shared schemas. Organizes by domain.
tags - — Folder per tag with split files. Best for large APIs. Recommended.
tags-split
- — 所有内容生成在一个文件中。适合小型 API。
single - — 拆分到多个文件:
split、petstore.ts、petstore.schemas.ts。适合中型 API。petstore.msw.ts - — 每个 OpenAPI 标签对应一个文件 + 共享模式。按领域组织代码。
tags - — 每个标签对应一个文件夹,内部拆分文件。适合大型 API。推荐使用。
tags-split
httpClient Option
httpClient 选项
For , , , and clients:
react-queryvue-querysvelte-queryswrts
output: {
client: 'react-query',
httpClient: 'fetch', // 'fetch' (default) | 'axios'
}For :
angular-queryts
output: {
client: 'angular-query',
httpClient: 'angular', // Uses Angular HttpClient
}对于 、、 和 客户端:
react-queryvue-querysvelte-queryswrts
output: {
client: 'react-query',
httpClient: 'fetch', // 'fetch' (默认) | 'axios'
}对于 :
angular-queryts
output: {
client: 'angular-query',
httpClient: 'angular', // 使用 Angular HttpClient
}Configuration Reference
配置参考
Config Structure
配置结构
ts
import { defineConfig } from 'orval';
export default defineConfig({
[projectName]: {
input: InputOptions,
output: OutputOptions,
hooks: HooksOptions,
},
});Multiple projects can share the same config file with different input/output settings.
ts
import { defineConfig } from 'orval';
export default defineConfig({
[projectName]: {
input: InputOptions,
output: OutputOptions,
hooks: HooksOptions,
},
});多个项目可共享同一个配置文件,使用不同的输入/输出设置。
Input Options
输入选项
ts
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',
},
},
],
},
}ts
input: {
target: './spec.yaml', // OpenAPI 规范的路径或 URL(必填)
override: {
transformer: './transform.js', // 生成前转换规范
},
filters: {
mode: 'include', // 'include' | 'exclude'
tags: ['pets', /health/], // 按 OpenAPI 标签过滤
schemas: ['Pet', /Error/], // 按模式名称过滤
},
parserOptions: {
headers: [ // 远程规范 URL 的认证头
{
domains: ['api.example.com'],
headers: {
Authorization: 'Bearer YOUR_TOKEN',
'X-API-Key': 'your-api-key',
},
},
],
},
}Output Options
输出选项
ts
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' } },
mock: true, // Generate MSW handlers (boolean or config object)
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)
}ts
output: {
target: './src/api/endpoints.ts', // 输出路径(必填)
client: 'react-query', // 客户端类型(见上方表格)
httpClient: 'fetch', // 'fetch' (默认) | 'axios' | 'angular'
mode: 'tags-split', // 'single' | 'split' | 'tags' | 'tags-split'
schemas: './src/api/model', // 模型类型的输出路径
operationSchemas: './src/api/params', // 操作衍生类型的独立输出路径
workspace: 'src/', // 所有文件的基础文件夹
fileExtension: '.ts', // 自定义文件扩展名
namingConvention: 'camelCase', // 文件命名:camelCase | PascalCase | snake_case | kebab-case
indexFiles: true, // 生成 index.ts 桶文件
clean: true, // 生成前清理输出目录
prettier: true, // 使用 Prettier 格式化
biome: true, // 使用 Biome 格式化
headers: true, // 生成请求头参数
baseUrl: '/api/v2', // API 基础 URL
// 或从规范中获取:
// baseUrl: { getBaseUrlFromSpecification: true, index: 0, variables: { environment: 'api.dev' } },
mock: true, // 生成 MSW 处理器(布尔值或配置对象)
docs: true, // 生成 TypeDoc 文档
// docs: { configPath: './typedoc.config.mjs' },
allParamsOptional: true, // 所有参数设为可选(路径参数除外)
urlEncodeParameters: true, // 对路径/查询参数进行 URL 编码
optionsParamRequired: false, // 设为必填的选项参数
propertySortOrder: 'Specification', // 'Alphabetical' | 'Specification'
tsconfig: './tsconfig.json', // 自定义 tsconfig 路径
override: { ... }, // 高级覆盖配置(见下文)
}Multiple API Specs
多 API 规范配置
ts
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' },
},
});ts
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' },
},
});Filter Endpoints
过滤端点
ts
input: {
target: './spec.yaml',
filters: {
mode: 'include',
tags: ['pets'],
},
}ts
input: {
target: './spec.yaml',
filters: {
mode: 'include',
tags: ['pets'],
},
}Detailed Guides
详细指南
When the user's question involves a specific topic below, read the corresponding file from this skill's directory.
| Topic | File | Load when user asks about... |
|---|---|---|
| TanStack Query / SWR | tanstack-query.md | React Query, Vue Query, Svelte Query, Solid Query, SWR, query hooks, invalidation, infinite queries, suspense, prefetch |
| Angular | angular.md | Angular Query, Angular HttpClient, signals, inject functions, Angular services, providedIn |
| SolidStart | solid-start.md | SolidStart, @solidjs/router, query(), action(), createAsync, revalidate |
| Custom HTTP / Auth | custom-http-clients.md | Custom mutator, authentication, tokens, interceptors, custom fetch/axios, baseURL, hook-based mutator |
| Zod Validation | zod-validation.md | Zod schemas, validation, runtime validation, coerce, strict, preprocess |
| Mocking / MSW | mocking-msw.md | MSW mocks, testing, test setup, faker, Vitest, mock handlers, useExamples |
| Hono Server | hono.md | Hono handlers, zValidator, composite routes, context types, server-side generation |
| Advanced Config | advanced-config.md | Type generation, enums, per-operation overrides, FormData, JSDoc, params serializer, full example |
| Tooling / Workflow | tooling-workflow.md | Programmatic API, transformers, hooks, NDJSON streaming, MCP, afterAllFilesWrite |
当用户的问题涉及以下特定主题时,请从本技能的目录中读取对应文件。
| 主题 | 文件 | 当用户询问以下内容时加载... |
|---|---|---|
| TanStack Query / SWR | tanstack-query.md | React Query、Vue Query、Svelte Query、Solid Query、SWR、查询钩子、失效、无限查询、Suspense、预获取 |
| Angular | angular.md | Angular Query、Angular HttpClient、信号、注入函数、Angular 服务、providedIn |
| SolidStart | solid-start.md | SolidStart、@solidjs/router、query()、action()、createAsync、重新验证 |
| 自定义 HTTP / 认证 | custom-http-clients.md | 自定义变更器、认证、令牌、拦截器、自定义 fetch/axios、baseURL、基于钩子的变更器 |
| Zod 验证 | zod-validation.md | Zod 模式、验证、运行时验证、强制转换、严格模式、预处理 |
| 模拟 / MSW | mocking-msw.md | MSW 模拟、测试、测试配置、faker、Vitest、模拟处理器、useExamples |
| Hono 服务器 | hono.md | Hono 处理器、zValidator、复合路由、上下文类型、服务端生成 |
| 高级配置 | advanced-config.md | 类型生成、枚举、按操作覆盖、FormData、JSDoc、参数序列化、完整示例 |
| 工具链 / 工作流 | tooling-workflow.md | 程序化 API、转换器、钩子、NDJSON 流、MCP、afterAllFilesWrite |
OpenAPI Specification Best Practices
OpenAPI 规范最佳实践
- Use unique for every operation — Orval uses these for function and hook names
operationId - Define reusable schemas in — reduces duplication in generated types
components/schemas - Use tags to group operations — works with and
tagsmodestags-split - Define response types for all operations — enables full type safety
- Mark required fields — affects optional/required in generated TypeScript interfaces
- Use for numeric enums — generates readable const names
x-enumNames - Provide values — used by mock generation when
exampleuseExamples: true - Use content type for streaming endpoints — enables typed NDJSON generation
application/x-ndjson
- 为每个操作使用唯一的 — Orval 使用该 ID 生成函数和钩子名称
operationId - 在 中定义可复用模式 — 减少生成类型中的重复代码
components/schemas - 使用标签对操作进行分组 — 与 和
tags模式兼容tags-split - 为所有操作定义响应类型 — 实现完整的类型安全
- 标记必填字段 — 影响生成的 TypeScript 接口中的可选/必填属性
- 对数值枚举使用 — 生成可读性强的常量名称
x-enumNames - 提供 值 — 当
example时,模拟生成会使用这些值useExamples: true - 对流式端点使用 内容类型 — 启用类型化 NDJSON 生成
application/x-ndjson
CLI Reference
CLI 参考
bash
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 generationbash
orval # 使用自动发现的配置生成代码
orval --config ./api/orval.config.ts # 指定配置文件
orval --project petstore # 运行特定项目(可多个)
orval --watch # 监听模式
orval --watch ./src # 监听指定目录
orval --clean # 清理生成的文件
orval --prettier # 使用 Prettier 格式化
orval --biome # 使用 Biome 格式化
orval --tsconfig ./src/tsconfig.json # 自定义 tsconfig 路径
orval --mode split # 覆盖输出模式
orval --client react-query # 覆盖客户端类型
orval --mock # 覆盖模拟生成配置
orval --input ./spec.yaml --output ./api.ts # 直接生成(无需配置文件)