目录

  • OpenAPI Typescript Codegen 的使用
    • 安装:`npm install openapi-typescript-codegen –save-dev`
    • 用法:`openapi –input ./spec.json –output ./generated –client xhr`
      • ❎ 解决报错:zsh: command not found: openapi
        • 原因:openapi-typescript-codegen 安装后没有将其加入到系统的 PATH 中,或者需要使用 npx 命令来运行它。
        • 解决方法1:使用 npx 运行 openapi 命令:`npx openapi –input http://localhost:3000/swagger.json –output ./generated –client axios`
        • 解决方法2:添加 openapi-typescript-codegen 到全局环境中:`npm install -g openapi-typescript-codegen`
        • 解决方法3:确保 node_modules/.bin 目录在你的 PATH 中:

传统情况下,对于每个请求前端都要单独编写代码。至少也得写一个请求路径。
现在使用 OpenAPI Typescript Codegen ,只需一个指令就能生成所有调用后端接口的代码了。

OpenAPI Typescript Codegen 的使用

安装:npm install openapi-typescript-codegen --save-dev

npm install openapi-typescript-codegen --save-dev

用法:openapi --input ./spec.json --output ./generated --client xhr

$ openapi --helpUsage: openapi [options]Options:-V, --version output the version number-i, --input <value> OpenAPI specification, can be a path, url or string content (required)-o, --output <value>Output directory (required)-c, --client <value>HTTP client to generate [fetch, xhr, node, axios, angular] (default: "fetch")--name <value>Custom client class name--useOptionsUse options instead of arguments--useUnionTypes Use union types instead of enums--exportCore <value>Write core files to disk (default: true)--exportServices <value>Write services to disk (default: true)--exportModels <value>Write models to disk (default: true)--exportSchemas <value> Write schemas to disk (default: false)--indent <value>Indentation options [4, 2, tab] (default: "4")--postfixServices Service name postfix (default: "Service")--postfixModels Model name postfix--request <value> Path to custom request file-h, --helpdisplay help for commandExamples$ openapi --input ./spec.json --output ./generated$ openapi --input ./spec.json --output ./generated --client xhr

❎ 解决报错:zsh: command not found: openapi

原因:openapi-typescript-codegen 安装后没有将其加入到系统的 PATH 中,或者需要使用 npx 命令来运行它。
解决方法1:使用 npx 运行 openapi 命令:npx openapi --input http://localhost:3000/swagger.json --output ./generated --client axios

npx 是一个用于运行项目依赖中的可执行文件的工具,可以确保正确查找和运行 openapi。

npx openapi --input http://localhost:3000/swagger.json --output ./generated --client axios
解决方法2:添加 openapi-typescript-codegen 到全局环境中:npm install -g openapi-typescript-codegen

使用 -g 标志将该工具安装到全局环境中,然后应该就能够在命令行中直接运行 openapi。

npm install -g openapi-typescript-codegen
解决方法3:确保 node_modules/.bin 目录在你的 PATH 中:

可以将 node_modules/.bin 目录添加到你的 PATH 环境变量中,以便在命令行中直接运行项目依赖中的可执行文件。这通常可以通过修改你的 shell 配置文件(如 .zshrc 或 .bashrc)来实现。
以下是一个示例命令:

export PATH="./node_modules/.bin:$PATH"

根据你的操作系统和 Shell 类型进行相应的配置。