给你推荐一款快速通过 typescript 生成 jsonschema 的包处理器
fast-typescript-to-jsonschema
Typescript 生成 jsonschema 数据插件
性能
案例
interface AAA {
a: number;
b: string;
c: boolean;
}
解析器 | 解析耗时 |
---|---|
fast-typescript-to-jsonschema | 15ms |
typescript-json-schema | 5430ms |
特性
- 编译Typescript文件以获取完整的类型信息
- 将所需的属性、继承、注释、属性初始值转换为jsonschema
使用
1.安装依赖
yarn add fast-typescript-to-jsonschema -D
2.创建type.ts
文件,内容如下:
interface ITest {
attr1: string;
attr2: number;
attr3?: boolean;
}
- 创建
test.js
文件,内容如下:
3.1 通过文件生成 jsonschema
const { default: genTypeSchema } = require('fast-typescript-to-jsonschema');
const path = require('path');
// 目标文件
const file = path.resolve(__dirname, './type.ts');
// 生成数据
genTypeSchema.genJsonDataFormFile(file);
// 获得当前文件对应的所有jsonschema数据
const json = genTypeSchema.genJsonData();
// 获得具体的某个type的jsonschema数据
const jsonSchema = genTypeSchema.getJsonSchema(file, 'ITest');
// 返回结果
console.log(jsonSchema);
3.2 通过 code 生成 jsonschema
const { default: genTypeSchema } = require('fast-typescript-to-jsonschema');
const code = `
interface ITest {
attr1: string;
attr2: number;
attr3?: boolean;
}
`
// generate data
genTypeSchema.genJsonDataFromCode(code);
// get all jsonschema data of current file
const json = genTypeSchema.genJsonData();
// get jsonschema of specific type
const jsonSchema = genTypeSchema.getJsonSchema('ITest');
// result
console.log(jsonSchema);
4.执行脚本
node ./test.js
jsonSchema
返回结果如下:
{
"additionalProperties": false,
"properties": {
"attr1": {
"type": "string",
},
"attr2": {
"type": "number",
},
"attr3": {
"type": "boolean",
},
},
"required": [
"attr1",
"attr2",
],
"type": "object",
}
- example 案例地址: github.com/yunke-yunfl…
注释
示例1
interface Interface_1 {
attr: string;
}
结果:
{
"additionalProperties": false,
"properties": {
"attr": {
"type": "string",
},
},
"required": [
"attr",
],
"type": "object",
}
示例2
interface Interface_4 {
attr: string[];
}
结果:
{
"additionalProperties": false,
"properties": {
"attr": {
"items": {
"type": "string",
},
"type": "array",
},
},
"required": [
"attr",
],
"type": "object",
}
更多支持的类型解析请看,目录如下:
贡献
我们非常欢迎您的贡献,您可以通过以下方式与我们共建。
转载自:https://juejin.cn/post/7205773311606554679