Yapi-to-TypeScript

260 阅读1分钟

YTT:fjc0k.github.io/yapi-to-typ…

使用方式

  1. yarn add yapi-to-typescript // 依赖
  2. npx ytt init // 根目录生成脚本

  1. 修改本地配置

    1. 获取token和id传入配置中

      1. 分类 id,可以设置多个。设为 0 时表示全部分类。
      2. 如果需要获取全部分类,同时排除指定分类,可以这样:[0, -20, -21],分类 ID 前面的负号表示排除
    2. 修改代码中的token和id (可自定义配置输出文件位置 接口id)

    3. import { defineConfig } from 'yapi-to-typescript';
      
      /**
       * 生成Api接口名称  Interface和ChangeCase数据类型参见node_modules\yapi-to-typescript\lib\esm\index.d.ts定义
       * @param interfaceInfo : Interface
       * @param changeCase:ChangeCase
       * @returns 请求响应接口名称--pascal命名
       */
      function genApiInterfaceName(interfaceInfo, changeCase) {
        const lastPath = interfaceInfo.parsedPath.dir.split('/').pop();
        return `${changeCase.pascalCase(lastPath)}${changeCase.pascalCase(interfaceInfo.parsedPath.name)}`;
      }
      
      export default defineConfig([
        {
          serverUrl: 'http://api.xxxx.cn/',//yapi首页地址
          typesOnly: true,
          target: 'typescript',
          reactHooks: {
            enabled: false,
          },
          prodEnvName: '', //项目名称
          outputFilePath: (interfaceInfo, changeCase) => {
            const filePathArr = interfaceInfo.path.split('/').slice(-2);
            const filePath = filePathArr.map((item) => changeCase.camelCase(item)).join('/');
            return `app/pages/${filePath}.ts`; //生成文件位置
          },
          getRequestDataTypeName: (interfaceInfo, changeCase) => {
            return `${genApiInterfaceName(interfaceInfo, changeCase)}Request`;
          },
          getResponseDataTypeName: (interfaceInfo, changeCase) => {
            return `${genApiInterfaceName(interfaceInfo, changeCase)}Response`;
          },
          dataKey: 'data',
          projects: [
            {  
              token: '',
              categories: [
                {
                  id: [],//可选择接口组下id或单个接口id  如为0则生成全部接口文件
                },
              ],
            },
          ],
        },
      ]);