1.前因
- 起因:使用ts开发面对服务端接口返回的数据类型多而杂,手写每个接口的 interface 并且兼容接口的嵌套类型,比较麻烦且耗时耗力,因此调研自动生成的interface接口类型
- 方案: 使用yapi-to-typescript生成 文档yapi-to-typescript
- 理由: 快,简单上头;开发时从master拉代码,修改ytt.config.ts配置中的token和id即可,然后执行npx ytt,便会生成我们本次开发所有接口的类型定义
2.yapi-to-typescript介绍
是一个代码生成工具,其可根据 YApi 或 Swagger 的接口定义生成 TypeScript 或 JavaScript 的接口类型及其请求函数代码。
3.安装+配置+使用
1.安装依赖 npm i yapi-to-typescript
2.配置 npx ytt init
3.生成 npx ytt
ytt.config.ts文件配置
import { defineConfig } from 'yapi-to-typescript';
export default defineConfig([
{
serverUrl: 'xxxx', //基于 YApi 的项目,此处填 YApi 首页地址
typesOnly: true, //是否只生成接口请求内容和返回内容的 TypeSript 类型,是则请求文件和请求函数都不会生成。
target: 'typescript', //要生成的目标代码类型。
reactHooks: {
// 支持生成 React Hooks 代码的相关配置。
enabled: false
},
prodEnvName: '测试环境',
outputFilePath: 'src/api/index.ts', //输出文件路径
requestFunctionFilePath: 'src/api/request.ts', //请求函数文件路径
dataKey: 'data',
projects: [
{
token: 'xxx',
categories: [
//分类列表
{
id: xxx, //项目id 打开项目 -> 点开分类 -> 复制浏览器地址栏 /api/cat_ 后面的数字。
getRequestFunctionName(interfaceInfo, changeCase) {
return changeCase.camelCase(interfaceInfo.parsedPath.name);
}
}
]
}
]
}
]);
4.修改token和ID配置
-
ytt.config.ts文件下修改配置【token,id】
-
执行npx ytt生成接口类型定义文件
-
在开发项目到下引入生成的api/index.ts文件去使用即可
b.
5.命令行方式实现
- 入口文件
#!/usr/bin/env node
const program = require('commander');
const createInterface = require('./yapi-to-typescript/index');
// yapi 相关工具 <token> <id> <pathName>
program.command('yapi')
.description('wb-tools接入yapi 工具相关配置')
.action(() => {
// token,id,pathName
createInterface();
})
program.parse(process.argv);
- index.js
const inquirer = require('inquirer');
const promptList = require('./promptList'); //checkbox
const path = require('path');
const shelljs = require('shelljs');
const fs = require('fs')
function createInterface() {
inquirer.prompt(promptList).then((answers) => {
methods(answers)
});
}
- promptList.js
module.exports = [{
type: 'Input',
message: '输入token',
name: 'token',
validate: function(value) { // 校验用户输入是否合法
var pass = value.replace(/\s+/g,"")
if (pass) {
return true;
}
return '请输入正确token';
}
},{
type: 'Input',
message: '输入id',
name: 'id',
validate: function(value) { // 校验用户输入是否合法
var pass = value.replace(/\s+/g,"")
if (pass.length>=4) {
return true;
}
return '请输入正确id';
}
},
{
type: 'Input',
message: '输入生成后放入对文件夹名称',
name: 'pathName',
validate: function(value) { // 校验用户输入是否合法
var pass = value.replace(/\s+/g,"")
if (pass) {
return true;
}
return '请输入正确文件夹名';
}
}]