Versi lanjutan dari https://github.com/xiag-ag/typescript-to-json-schema.
Terinspirasi oleh YousefED/typescript-json-schema
. Berikut daftar perbedaannya:
typeChecker.getTypeAtLocation()
(jadi mungkin tipe alias tetap benar)definitions
dalam skema JSON Proyek ini dimungkinkan oleh komunitas kontributor. Kami menerima kontribusi apa pun (masalah, kode, dokumentasi, contoh, pengujian,...). Silakan baca kode etik kami.
Jalankan generator skema dengan npx:
npx ts-json-schema-generator --path ' my/project/**/*.ts ' --type ' My.Type.Name '
Atau instal paketnya lalu jalankan
npm install --save ts-json-schema-generator
./node_modules/.bin/ts-json-schema-generator --path ' my/project/**/*.ts ' --type ' My.Type.Name '
Perhatikan bahwa platform yang berbeda (misalnya Windows) mungkin menggunakan pemisah jalur yang berbeda sehingga Anda mungkin harus menyesuaikan perintah di atas.
Perhatikan juga bahwa Anda perlu mengutip jalur dengan *
karena jika tidak, shell akan memperluas jalur dan oleh karena itu hanya meneruskan jalur pertama ke generator.
Secara default, generator baris perintah akan menggunakan file tsconfig.json
di direktori kerja saat ini, atau direktori induk pertama yang berisi file tsconfig.json
hingga root sistem file. Jika Anda ingin menggunakan file tsconfig.json
yang berbeda, Anda dapat menggunakan opsi --tsconfig
. Khususnya, jika Anda perlu menggunakan opsi kompilasi yang berbeda untuk tipe, Anda mungkin ingin membuat file tsconfig.json
terpisah untuk pembuatan skema saja.
-p, --path <path> Source file path
-t, --type <name> Type name
-i, --id <name> $id for generated schema
-f, --tsconfig <path> Custom tsconfig.json path
-e, --expose <expose> Type exposing (choices: "all", "none", "export", default: "export")
-j, --jsDoc <extended> Read JsDoc annotations (choices: "none", "basic", "extended", default: "extended")
--markdown-description Generate `markdownDescription` in addition to `description`.
--functions <functions> How to handle functions. `fail` will throw an error. `comment` will add a comment. `hide` will treat the function like a NeverType or HiddenType.
(choices: "fail", "comment", "hide", default: "comment")
--minify Minify generated schema (default: false)
--unstable Do not sort properties
--strict-tuples Do not allow additional items on tuples
--no-top-ref Do not create a top-level $ref definition
--no-type-check Skip type checks to improve performance
--no-ref-encode Do not encode references
-o, --out <file> Set the output file (default: stdout)
--validation-keywords [value] Provide additional validation keywords to include (default: [])
--additional-properties Allow additional properties for objects with no index signature (default: false)
-V, --version output the version number
-h, --help display help for command
// main.js
const tsj = require ( "ts-json-schema-generator" ) ;
const fs = require ( "fs" ) ;
/** @type {import('ts-json-schema-generator/dist/src/Config').Config} */
const config = {
path : "path/to/source/file" ,
tsconfig : "path/to/tsconfig.json" ,
type : "*" , // Or <type-name> if you want to generate schema for that one type only
} ;
const outputPath = "path/to/output/file" ;
const schema = tsj . createGenerator ( config ) . createSchema ( config . type ) ;
const schemaString = JSON . stringify ( schema , null , 2 ) ;
fs . writeFile ( outputPath , schemaString , ( err ) => {
if ( err ) throw err ;
} ) ;
Jalankan generator skema melalui node main.js
.
Memperluas pemformatan bawaan dapat dilakukan dengan membuat pemformat khusus dan menambahkannya ke pemformat utama:
// my-function-formatter.ts
import { BaseType , Definition , FunctionType , SubTypeFormatter } from "ts-json-schema-generator" ;
import ts from "typescript" ;
export class MyFunctionTypeFormatter implements SubTypeFormatter {
// You can skip this line if you don't need childTypeFormatter
public constructor ( private childTypeFormatter : TypeFormatter ) { }
public supportsType ( type : BaseType ) : boolean {
return type instanceof FunctionType ;
}
public getDefinition ( type : FunctionType ) : Definition {
// Return a custom schema for the function property.
return {
type : "object" ,
properties : {
isFunction : {
type : "boolean" ,
const : true ,
} ,
} ,
} ;
}
// If this type does NOT HAVE children, generally all you need is:
public getChildren ( type : FunctionType ) : BaseType [ ] {
return [ ] ;
}
// However, if children ARE supported, you'll need something similar to
// this (see src/TypeFormatter/{Array,Definition,etc}.ts for some examples):
public getChildren ( type : FunctionType ) : BaseType [ ] {
return this . childTypeFormatter . getChildren ( type . getType ( ) ) ;
}
}
import { createProgram , createParser , SchemaGenerator , createFormatter } from "ts-json-schema-generator" ;
import { MyFunctionTypeFormatter } from "./my-function-formatter.ts" ;
import fs from "fs" ;
const config = {
path : "path/to/source/file" ,
tsconfig : "path/to/tsconfig.json" ,
type : "*" , // Or <type-name> if you want to generate schema for that one type only
} ;
// We configure the formatter an add our custom formatter to it.
const formatter = createFormatter ( config , ( fmt , circularReferenceTypeFormatter ) => {
// If your formatter DOES NOT support children, e.g. getChildren() { return [] }:
fmt . addTypeFormatter ( new MyFunctionTypeFormatter ( ) ) ;
// If your formatter DOES support children, you'll need this reference too:
fmt . addTypeFormatter ( new MyFunctionTypeFormatter ( circularReferenceTypeFormatter ) ) ;
} ) ;
const program = createProgram ( config ) ;
const parser = createParser ( program , config ) ;
const generator = new SchemaGenerator ( program , parser , formatter , config ) ;
const schema = generator . createSchema ( config . type ) ;
const outputPath = "path/to/output/file" ;
const schemaString = JSON . stringify ( schema , null , 2 ) ;
fs . writeFile ( outputPath , schemaString , ( err ) => {
if ( err ) throw err ;
} ) ;
Mirip dengan pemformatan khusus, memperluas penguraian bawaan bekerja dengan cara yang hampir sama:
// my-constructor-parser.ts
import { Context , StringType , ReferenceType , BaseType , SubNodeParser } from "ts-json-schema-generator" ;
// use typescript exported by TJS to avoid version conflict
import ts from "ts-json-schema-generator" ;
export class MyConstructorParser implements SubNodeParser {
supportsNode ( node : ts . Node ) : boolean {
return node . kind === ts . SyntaxKind . ConstructorType ;
}
createType ( node : ts . Node , context : Context , reference ?: ReferenceType ) : BaseType | undefined {
return new StringType ( ) ; // Treat constructors as strings in this example
}
}
import { createProgram , createParser , SchemaGenerator , createFormatter } from "ts-json-schema-generator" ;
import { MyConstructorParser } from "./my-constructor-parser.ts" ;
import fs from "fs" ;
const config = {
path : "path/to/source/file" ,
tsconfig : "path/to/tsconfig.json" ,
type : "*" , // Or <type-name> if you want to generate schema for that one type only
} ;
const program = createProgram ( config ) ;
// We configure the parser an add our custom parser to it.
const parser = createParser ( program , config , ( prs ) => {
prs . addNodeParser ( new MyConstructorParser ( ) ) ;
} ) ;
const formatter = createFormatter ( config ) ;
const generator = new SchemaGenerator ( program , parser , formatter , config ) ;
const schema = generator . createSchema ( config . type ) ;
const outputPath = "path/to/output/file" ;
const schemaString = JSON . stringify ( schema , null , 2 ) ;
fs . writeFile ( outputPath , schemaString , ( err ) => {
if ( err ) throw err ;
} ) ;
interface
enum
union
, tuple
, type[]
Date
, RegExp
, jenis URL
string
, boolean
, tipe number
"value"
, 123
, true
, false
, null
, literal undefined
typeof
keyof
Promise<T>
dibuka ke T
@format
) yarn --silent run run --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'
yarn --silent run debug --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'
Dan terhubung melalui protokol debugger.
AST Explorer luar biasa bagi pengembang alat ini!
Penerbitan ditangani oleh proses pra-rilis 2 cabang, yang dikonfigurasi publish-auto.yml
. Semua perubahan harus didasarkan pada cabang default next
, dan dipublikasikan secara otomatis.
next
di NPM. Hasilnya dapat diinstal dengan npm install ts-json-schema-generator@next
next
, harap gunakan strategi squash and merge
.next
ke stable
menggunakan tautan perbandingan ini.next
ke stable
, harap gunakan strategi create a merge commit
.