首页 前端知识 TypeScript到JSON Schema生成器:ts-json-schema-generator

TypeScript到JSON Schema生成器:ts-json-schema-generator

2025-02-27 11:02:02 前端知识 前端哥 364 696 我要收藏

TypeScript到JSON Schema生成器:ts-json-schema-generator

ts-json-schema-generatorGenerate JSON schema from your Typescript sources项目地址:https://gitcode.com/gh_mirrors/ts/ts-json-schema-generator

1. 项目介绍

ts-json-schema-generator 是一个用于从TypeScript源代码自动生成JSON Schema的工具。这个项目由Vega维护,它的主要目标是帮助开发者将他们的类型定义转化为可验证的数据模式,以便在API交互或者客户端数据校验中使用。

该库支持自定义配置,包括指定源文件路径、选择特定类型生成JSON Schema,以及自定义$Id和JsDoc注解的处理方式等。此外,它还提供了一个命令行接口(CLI)方便快速生成JSON Schema。

2. 项目快速启动

安装

通过npm安装ts-json-schema-generator:

npm install --save ts-json-schema-generator

命令行使用

生成JSON Schema:

npx ts-json-schema-generator \
  --path 'my/project/**/*.ts' \ 
  --type 'MyTypeName'

或在本地环境中运行:

./node_modules/.bin/ts-json-schema-generator \
  --path 'my/project/**/*.ts' \ 
  --type 'MyTypeName'

程序化使用

在你的Node.js应用程序中,你可以这样使用:

const tsj = require('ts-json-schema-generator');
const fs = require('fs');

// 配置项
const config = {
  path: 'path/to/source/file',
  tsconfig: 'path/to/tsconfig.json', // 可选
  type: 'MyTypeName', // 或者指定要生成的单个类型名
};

const outputPath = 'path/to/output/file';
const schemaGen = tsj.createGenerator(config);
const schema = schemaGen.createSchema(config.type);

const schemaStr = JSON.stringify(schema, null, 2);
fs.writeFile(outputPath, schemaStr, (err) => {
  if (err) throw err;
});

3. 应用案例和最佳实践

  • API校验: 将生成的JSON Schema应用于服务器端,校验客户端发送的请求数据。
  • 客户端数据绑定: 在前端框架中,如Angular或React,利用JSON Schema进行表单验证和自动模型绑定。
  • 数据交换规范: 定义微服务间的数据交换格式,确保正确性。

最佳实践:

  1. 使用TypeScript的类型注解来定义清晰的数据结构。
  2. 当需要生成多个类型的schema时,分别调用createSchema()方法。
  3. 根据项目需求调整配置,例如设置自定义$id,以符合你的命名规范。

4. 典型生态项目

  • typescript-json-schema: 另一个流行的JSON Schema生成库,可以作为替代方案。
  • ajv: 一个高效的JSON Schema验证库,与ts-json-schema-generator配合使用进行数据校验。
  • json-editor: 一个基于JSON Schema的JSON编辑器,可以在浏览器端展示并编辑数据。

以上就是ts-json-schema-generator的基本介绍及使用指南。借助此项目,您可以轻松地将TypeScript类型转换成强大的JSON Schema规范,提升数据一致性并简化开发流程。

ts-json-schema-generatorGenerate JSON schema from your Typescript sources项目地址:https://gitcode.com/gh_mirrors/ts/ts-json-schema-generator

转载请注明出处或者链接地址:https://www.qianduange.cn//article/21624.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!