{"id":13495785,"url":"https://github.com/reeli/ts-codegen","last_synced_at":"2025-07-24T22:33:35.343Z","repository":{"id":55092531,"uuid":"191906296","full_name":"reeli/ts-codegen","owner":"reeli","description":"Typescript code generator from swagger. 一个生成前端接口层代码和对应 TypeScript 定义的工具。","archived":false,"fork":false,"pushed_at":"2023-11-28T05:52:50.000Z","size":1293,"stargazers_count":55,"open_issues_count":0,"forks_count":10,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-30T13:24:37.384Z","etag":null,"topics":["codegen","swagger","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/reeli.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2019-06-14T08:31:43.000Z","updated_at":"2024-08-24T07:19:59.000Z","dependencies_parsed_at":"2023-11-28T06:44:19.744Z","dependency_job_id":null,"html_url":"https://github.com/reeli/ts-codegen","commit_stats":null,"previous_names":[],"tags_count":69,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reeli%2Fts-codegen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reeli%2Fts-codegen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reeli%2Fts-codegen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reeli%2Fts-codegen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/reeli","download_url":"https://codeload.github.com/reeli/ts-codegen/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227370657,"owners_count":17770706,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["codegen","swagger","typescript"],"created_at":"2024-07-31T19:01:38.165Z","updated_at":"2024-12-01T04:20:01.430Z","avatar_url":"https://github.com/reeli.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# TS Codegen\n\n[![Build Status](https://github.com/reeli/ts-codegen/workflows/test/badge.svg)](https://travis-ci.com/github/reeli/ts-codegen/actions)\n[![codecov](https://codecov.io/gh/reeli/ts-codegen/branch/master/graph/badge.svg?style=flat-square)](https://codecov.io/gh/reeli/ts-codegen)\n[![License](https://img.shields.io/npm/l/@ts-tool/ts-codegen.svg?style=flat-square)](https://npmjs.org/package/@ts-tool/ts-codegen)\n[![NPM](https://img.shields.io/npm/v/@ts-tool/ts-codegen-cli.svg?style=flat-square)](https://npmjs.org/package/@ts-tool/ts-codegen-cli)\n\nTS Codegen 是一个用于生成「前端接口层代码」以及对应「TypeScript 定义」的工具。你只需要提供一个 Swagger 或 Openapi 的 JSON/YML 文件，它就可以为您生成相应的代码。\n\n## 为什么使用 TS Codegen？\n\n1. **简单易用**：只需一个 cli 命令行工具和一个配置文件即可使用。\n2. **灵活性高**：不依赖于具体的 HTTP client，你可以用它集成任何一个你期望的 HTTP client，不限于 axios 和 fetch。\n3. **完整的类型定义**：生成代码包含了完整的类型定义，包括请求的入参以及响应数据的类型定义。通过生成的函数，就可以直接获取到请求的入参和响应数据的类型定义。\n4. **降低前后端集成成本**：特别是当后端接口发生变动时，只需要重新执行一下 cli，就能立刻知道后端发生了哪些改动。\n5. **支持多版本 Swagger**：同时支持 Swagger2 和 Swagger3 (OpenAPI)。\n6. **对 Tree Shaking 友好**：生成代码都是由纯函数组成，方便 webpack/rollup 等工具进行 Tree Shaking\n7. **支持多种框架**：能够应用到 ReactNative、React、Vue、Angular 等项目。\n\n## 快速尝试 Try it\n\n可以通过下面的命令进行快速尝试 [example](https://github.com/reeli/ts-codegen-examples) ：\n\n```bash\ngit clone https://github.com/reeli/ts-codegen-examples\ncd  ts-codegen-examples\nnpm install\nnpx ts-codegen\n```\n\n然后我们就可以在 `clients` 目录下看到生成的结果，并开始使用（参考 src/index.ts 中的代码）。\n\n## 开始\n\n1. 安装\n\n   `npm install @ts-tool/ts-codegen-cli -D`\n\n2. 生成配置文件\n\n   `npx ts-codegen init`\n\n   这个命令会在你的 project 根目录下生成一个配置文件：ts-codegen.config.json。\n\n3. 修改配置文件\n\n   根据自己的需求修改文件 ts-codegen.config.json，配置必填的 `requestCreateLib` 和 `apiSpecsPaths`\n   参数后，即可使用。参数说明详见 [附录：TS Codegen Config 参数说明](https://github.com/reeli/ts-codegen#%E9%99%84%E5%BD%95ts-codegen-config-%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E)。\n\n4. 执行命令\n\n   cd 到你项目的根目录下，执行如下命令：\n\n   ```bash\n   npx ts-codegen\n   ```\n\n   然后就可以在配置的 `clients` 目录下看到生成的结果，并开始使用。\n\n## 常见问题\n\n**1. 通过工具生成的代码格式都是双引号，但是我项目上使用的是单引号，应该怎么办？**\n\n可以先使用 ts-codegen 命令生成 API Requests，然后再通过自己项目的 prettier 格式化一次\n\n```json\n{\n  \"api\": \"npx ts-codegen \u0026\u0026 prettier --write src/apis/*.ts\"\n}\n```\n\n**2. 出现 \"Error: Cannot find module 'tslib'\"，应该怎么办？**\n\n请升级到 ≥3.1.2 版本\n\n**3. Swagger 生成的 response 类型和后端最终返回的数据结构不一致怎么办？**\n\n后端返回的 response 数据可能有一个统一的数据结构，然而这个结构在 swagger 中又没有定义，导致 swagger 生成的 response 类型和后端最终返回的数据结构不一致。举个例子，后端返回的 response 数据结构如下：\n\n```json5\n{\n  data: {}, // 响应数据\n  message: \"\",\n  code: \"\",\n}\n```\n\n这里的 data 才是我们在 swagger 里真正定义的 response，因此前端需要对 response 的类型进行修改。比如我们可以定一个 ResponseWrapper 类型，再把生成的 response 类型传进去：\n\n```ts\ninterface RespWrapper\u003cTData\u003e {\n  data: TData;\n  message: string | null;\n  code: number;\n}\n\nexport const createRequest = \u003cTReq, TResp = any\u003e(\n  _: string,\n  requestConfigCreator: (args: TReq) =\u003e AxiosRequestConfig,\n) =\u003e {\n  return (args: TReq) =\u003e {\n    return axiosInstance.request\u003cTReq, RespWrapper\u003cTResp\u003e\u003e(requestConfigCreator(args));\n  };\n};\n```\n\n**4. 在 `apiSpecsPaths` 中配置多个服务，每个服务的域名都不一样，应该如何处理？**\n\n使用 `withServiceNameInHeader`，具体使用方式请查看[文档](https://github.com/reeli/ts-codegen#%E9%99%84%E5%BD%95ts-codegen-config-%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E)。\n\n**5. 实现 requestCreateMethod （比如`createRequest`）时，可以不发起真正的 API call 吗？**\n\n当然可以，`requestCreateMethod` 可以发起真正的 API call, 也可以只返回请求需要用到的配置项，比如：\n\n```ts\nimport { AxiosRequestConfig } from \"axios\";\n\nexport const createRequestConfig = \u003cTReq, TResp = any\u003e(\n  _: string,\n  requestConfigCreator: (args: TReq) =\u003e AxiosRequestConfig,\n) =\u003e {\n  const fn = (args: TReq) =\u003e {\n    return requestConfigCreator(args);\n  };\n\n  return Object.assign(fn, {\n    TReq: {} as TReq,\n    TResp: {} as TResp,\n  });\n};\n```\n\n## 使用核心依赖进行二次封装\n\n如果您想自己编写命令行工具，或者对核心功能进行一些修改，可以使用 `npm intall @ts-tool/ts-codegen-core` 安装核心依赖包，然后根据核心依赖包提供的方法进行二次封装。\n\n## 版本迁移\n\n请参考[版本迁移文档](https://github.com/reeli/ts-codegen/blob/master/docs/migration.md)\n\n## 附录：TS Codegen Config 参数说明\n\n- **`requestCreateMethod`: String [可选项]**\n\n  表示方法或函数名，用于创建发起请求的函数。默认值为 createRequest。你可以自己实现 `requestCreateMethod`\n  方法，也可以参考[示例代码](https://github.com/reeli/ts-codegen/tree/master/packages/ts-codegen-core/examples/utils)。下面是一个基于 axios\n  实现的 createRequest 示例:\n\n  ```typescript\n  import axios, { AxiosRequestConfig } from \"axios\";\n\n  const axiosInstance = axios.create({\n    baseURL: \"https://petstore.swagger.io\",\n  });\n\n  export const createRequest = \u003cTReq, TResp = any\u003e(\n    _: string,\n    requestConfigCreator: (args: TReq) =\u003e AxiosRequestConfig,\n  ) =\u003e {\n    return (args: TReq) =\u003e {\n      return axiosInstance.request\u003cTResp\u003e(requestConfigCreator(args));\n    };\n  };\n  ```\n\n- **`requestCreateLib`: String [必填项]**\n\n  表示 `requestCreateMethod` 所在的文件路径。用于导入 `requestCreateMethod` 方法。\n\n- **`apiSpecsPaths`: Array [必填项]**\n\n  用于配置 swagger/openapi 文件所在的地址(`path`)，以及它对应的生成文件的名称(`name`)。其中 `path` 既可以是远端 url，也可以是本地 swagger/openapi 所在的文件路径。CLI\n  工具会根据你的配置，自动读取远端或者本地文件，生成对应代码。目前支持的文件格式有 `.json`, `.yaml`, `.yml`。\n\n  ```json5\n  {\n    apiSpecsPaths: [\n      {\n        path: \"https://petstore.swagger.io/v2/swagger.json\", // 远程获取 Swagger 文档（json 格式）\n        name: \"PetStoreService1\",\n      },\n      {\n        path: \"https://petstore.swagger.io/v2/swagger.yaml\", // 远程获取 Swagger 文档（yaml 格式）\n        name: \"PetStoreService2\",\n      },\n      {\n        path: \"./examples/swagger.json\", // 从本地文件读取 Swagger 文档（json 格式）\n        name: \"SwaggerService\",\n      },\n      {\n        path: \"./examples/openapi.json\", // 从本地文件读取 OpenAPI 文档（json 格式）\n        name: \"OpenApiService\",\n      },\n      {\n        path: \"./examples/demo.yaml\", // 从本地文件读取 Swagger 文档（yaml 格式）\n        name: \"DemoService\",\n      },\n    ],\n  }\n  ```\n\n  \u003e 注意：提供的 Swagger/Openapi json 中，必须保证每个 API 请求都包含属性 `operationId`。\n\n- **`outputFolder`: String [可选项]**\n\n  表示输出生成代码的目录名称。默认值为 clients。支持配置子路径，比如：`clients/apis`\n\n- **`options`: Object [可选项]**\n\n  表示一些额外配置。其中，`typeWithPrefix` 和 `backwardCompatible` 仅在需要兼容老版本时进行配置。\n\n  - **`typeWithPrefix`: Boolean [可选项]，默认值: false**\n\n    如果设置为 true，会为所有的生成的 interface 和 type 加上前缀，其中 interface 加上 `I` 前缀，type 加上 `T` 前缀。\n\n  - **`backwardCompatible`: Boolean [可选项]，默认值: false**\n\n    用于兼容老版本，一般不推荐设置为 true。如果你使用了之前的版本，并且希望尽可能兼容以前的老版本，可以将其设置为 true。\n\n  - **`withComments`: Boolean [可选项]，默认值: false**\n\n    用于设置在生成代码中是否显示注解。比如你在 swagger 文档中通过 `summary`, `description` 等字段，为一个 API 添加了描述，你就可以通过这个开关来控制这个描述是否显示在最终的生成代码中。\n\n  - **`withServiceNameInHeader`: Boolean [可选项]，默认值: false**\n\n    用于设置在生成代码中是否将 service name（也就是在 apiSpecsPaths 中配置 的 name 参数） 显示到 headers 中。比如你在 `ts-codegen.config.json` 中, 配置了\n    apiSpecsPaths 其中一个服务的 `name` 为 `PetStoreService1`，那么最终生成的代码中，每个请求的 headers 上都会带上 这个 service name。例如：\n\n    ```ts\n    import { createRequestConfig } from \"service/createRequestConfig\";\n\n    const serviceName = \"fileService\";\n\n    export const uploadFile = createRequestConfig(\"uploadFile\", () =\u003e ({\n      url: \"/v1/debit-card/link\",\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\", \"Service-Name\": serviceName },\n    }));\n    ```\n\n    只有当你配置的 service（也就是 apiSpecsPaths 中配置的 items）包含不同的域名时，你才需要配置这个属性，否则你无须关心它。这是因为生成请求的 url 上没有包含 host 信息，如果我们将\n    service name 生成到代码中，我们就可以通过它来映射不同的域名。比如，通过 axios 的 interceptor 统一拦截并处理：\n\n    ```ts\n    axios.interceptors.request.use(\n      (config) =\u003e {\n        if (config.headers[\"Service-Name\"]) {\n          const mapping = {\n            fileService: \"http://file.service.com\",\n            accountService: \"http://account.service.com\",\n          };\n\n          config.baseURL = mapping[config.headers[\"Service-Name\"]];\n\n          delete config.headers[\"Service-Name\"];\n\n          return config;\n        }\n        return config;\n      },\n      (error) =\u003e Promise.reject(error),\n    );\n    ```\n\n## 附录：配置模板\n\n```json5\n{\n  outputFolder: \"clients\",\n  // 支持配置子文件夹, eg: src/apis\n  requestCreateLib: \"../examples/utils/createRequest\",\n  requestCreateMethod: \"createRequest\",\n  apiSpecsPaths: [\n    {\n      path: \"https://petstore.swagger.io/v2/swagger.json\",\n      name: \"PetStoreService1\",\n    },\n    {\n      path: \"https://petstore.swagger.io/v2/swagger.yaml\",\n      name: \"PetStoreService2\",\n    },\n    {\n      path: \"./examples/swagger.json\",\n      name: \"SwaggerService\",\n    },\n    {\n      path: \"./examples/openapi.json\",\n      name: \"OpenApiService\",\n    },\n    {\n      path: \"./examples/demo.yaml\",\n      name: \"DemoService\",\n    },\n  ],\n  options: {\n    withComments: true,\n    typeWithPrefix: true,\n    backwardCompatible: true,\n  },\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freeli%2Fts-codegen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Freeli%2Fts-codegen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freeli%2Fts-codegen/lists"}