前言
日常项目开发过程中,如果项目中涉及到ts,就会涉及到一些接口数据的定义,
- ts强类型语言,在编译时就可以提示一些错误
- 可读性强,支持一些新特性,例如可选链 但是我们最烦的应该是数据类型定义,刚学ts时我会根据后台返回字段,自己一一去定义一遍,后来发现效率低下,慢慢对ts失去了兴趣,突然发现一个工具,香。
工具
openapi-typescript 我们公司用的swagger哦,记得提醒后端同学接口定义规范
编写运行脚本
import child_process from "child_process";
import fs from "fs";
import path from "path";
/**
*
* @param {string} url 文档地址
* @param {string} modelName 文档模块(例如:微服务下属于哪个服务)
* @param {fn} deal 自定义处理内容的方法
*/
export function build(url, modelName = "", deal) {
// const file = `def.ts`;
// const shell = `npx openapi-typescript@3.4.1 ${url} --output ${file}`;
const shell = `npx openapi-typescript https://petstore.swagger.io/v2/swagger.json --output petstore.ts`;
child_process.exec(shell, { cwd: path.resolve("./") }, (error, stdout, stderr) => {
error && console.log(`[error]\n`, error);
stdout && console.log(`[stdout]\n`, stdout);
stderr && console.log(`[stderr]\n`, stderr);
console.log("file", file);
const content = fs.readFileSync(file, { encoding: "utf8" });
// // 自定义处理
if (typeof deal === "function") content = deal(content);
// // 此处可以处理content内容然后写回去
// // 重写文件
fs.writeFileSync(file, content, { encoding: "utf8" });
});
}
使用
请在用到接口字段的地方,引入生成定义字段定义