Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Generates TypeScript from Java - JSON declarations, REST service client

License

NotificationsYou must be signed in to change notification settings

vojtechhabarta/typescript-generator

Repository files navigation

Maven CentralAppveyorStars

Quick links:Configuration parameters|Breaking changes|Release notes|Playground(beta)

typescript-generator

typescript-generator is a tool for generating TypeScript definition files (.d.ts) from Java JSON classes.If you have REST service written in Java (or another JVM language) using object to JSON mapping you can use typescript-generator to generate TypeScript interfaces from Java classes.

For example for this Java class:

publicclassPerson {publicStringname;publicintage;publicbooleanhasChildren;publicList<String>tags;publicMap<String,String>emails;}

typescript-generator outputs this TypeScript interface:

interfacePerson{name:string;age:number;hasChildren:boolean;tags:string[];emails:{[index:string]:string};}

Supported types include:

  • all Java primitive types with their corresponding wrappers (for exampleint andInteger,boolean andBoolean, etc.)
  • String
  • Date
  • enum
  • array
  • List andMap (including derived interfaces and implementation classes)
  • customized type mapping

For more details seeType Mapping Wiki page.

Note: typescript-generator works with compiled classes using Java reflection. It doesn't use source files (except for Javadoc feature).In Maven plugin this means either classes compiled from source files in the same module or classes added using<dependency> element.

Maven

In Maven build you can usetypescript-generator-maven-plugin like this:

<plugin>    <groupId>cz.habarta.typescript-generator</groupId>    <artifactId>typescript-generator-maven-plugin</artifactId>    <version>x.y.z</version>    <executions>        <execution>            <id>generate</id>            <goals>                <goal>generate</goal>            </goals>            <phase>process-classes</phase>        </execution>    </executions>    <configuration>        <jsonLibrary>jackson2</jsonLibrary>        <classes>            <class>cz.habarta.typescript.generator.Person</class>        </classes>        <outputKind>module</outputKind>    </configuration></plugin>

More complete sample can be foundhere.Detailed description how to configure typescript-generator-maven-plugin is on generatedsite.

Gradle

In Gradle build you can usecz.habarta.typescript-generator plugin like this:

plugins {    id'cz.habarta.typescript-generator' version'x.y.z'}generateTypeScript {    jsonLibrary='jackson2'    classes= ['cz.habarta.typescript.generator.sample.Person'    ]    outputKind='module'}

For the Kotlin Gradle DSL you can alternatively use thecz.habarta.typescript-generator plugin like this:

build.gradle.kts

importcz.habarta.typescript.generator.JsonLibraryimportcz.habarta.typescript.generator.TypeScriptFileTypeimportcz.habarta.typescript.generator.TypeScriptOutputKindplugins {    id("cz.habarta.typescript-generator") version"x.y.z"}tasks {    generateTypeScript {        jsonLibrary=JsonLibrary.jackson2        outputKind=TypeScriptOutputKind.module        outputFileType=TypeScriptFileType.implementationFile...    }}

You can run typescript-generator on demand usinggradle generateTypeScript commandor you can invoke it as part of another task by adding dependency from that task togenerateTypeScript task in Gradle build file.

More complete sample can be foundhere.Gradle plugin has the same features as Maven plugin, for detailed description see Maven generatedsite.

Direct invocation

If you do not use Maven or Gradle you can invoke typescript-generator directly usingTypeScriptGenerator.generateTypeScript() method.

Input classes

Input classes can be specified using several parameters:

  • classes - list of fully qualified class names, includes all listed classes and their dependencies,$ character is used for nested classes likecom.example.ClassName$NestedClassName
  • classPatterns - list of glob patterns likecom.example.*Json, includes all classes matched by the pattern, supported are* and** wildcards
  • classesFromJaxrsApplication - fully qualified name of JAX-RS application class, all classes used by application resources will be included, recommended if you have JAX-RS application class
  • classesFromAutomaticJaxrsApplication - valuetrue will include classes from automatically discovered REST resources, recommended if you have JAX-RS application withoutApplication subclass
  • excludeClasses - list of fully qualified class names, excluded classes will be mapped to TypeScriptany type, if excluded class is a resource then this resource will not be scanned for used classes

Note: it is possible to use multiple parameters at the same time.

For more details seeClass Names Glob Patterns andJAX RS Application Wiki pages.

Output parameters

Output is configured using several parameters:

  • outputKind (required parameter) - determines if and how module will be generated
    • values are:global,module,ambientModule
  • outputFileType - specifies TypeScript file type
    • values are:declarationFile (.d.ts) orimplementationFile (.ts)
  • outputFile - specifies path and name of output file

For more details seeModules and Namespaces page.

REST frameworks

Typescript-generator can generate not only TypeScript declarations for JSON Java classes but it can also generate client classes for REST services. Supported REST frameworks are JAX-RS and Spring. Client for JAX-RS service can be generated usinggenerateJaxrsApplicationClient parameter, client for Spring service can be generated usinggenerateSpringApplicationClient. Since Spring support is in separate module it is needed to add this module to typescript-generator dependencies. Here is example for Maven:

<plugin>    <groupId>cz.habarta.typescript-generator</groupId>    <artifactId>typescript-generator-maven-plugin</artifactId>    <version>${typescript-generator.version}</version>    <configuration>        <generateSpringApplicationClient>true</generateSpringApplicationClient>        ...    </configuration>    <dependencies>        <dependency>            <groupId>cz.habarta.typescript-generator</groupId>            <artifactId>typescript-generator-spring</artifactId>            <version>${typescript-generator.version}</version>        </dependency>    </dependencies></plugin>

Download

Releases are available from Maven Central Repository.Search for dependency information for your build toolor downloadtypescript-generator-core directly.

Wiki

For more detailed description of some topics seeWiki pages.

Architecture

TypeScriptGenerator has 3 main parts (ModelParser,ModelCompiler andEmitter) which work together to produce TypeScript declarations for specified Java classes.

           (Model)            (TsModel)ModelParser  ==>  ModelCompiler  ==>  Emitter         |         |         V         V        TypeProcessor
  • ModelParser reads Java JSON classes and their properties using Java reflections and createsModel.It usesTypeProcessors for finding used classes.For example if property type isList<Person> it discovers thatPerson class should be also parsed.ModelParsers are specific for each JSON library (for exampleJackson2Parser).
  • ModelCompiler transforms Java model to TypeScript model (Model class toTsModel class).It usesTypeProcessors for mapping Java types to TypeScript types (for example forint returnsnumber).
  • Emitter takesTsModel and produces TypeScript declaration file.

Links

Contributing

  • current major version supports Java 8 and later (version 1 supported Java 7 and 8)
  • keep pull requests small and focused (10 tips for better Pull Requests)
  • do not add dependencies unless previously discussed in issue

Code formatting

  • use 4 spaces for indentation in Java files
  • sort java imports alphabetically (including static imports), do not use wildcard (star) imports
  • please do not reformat whole files in IDE (prevent accidental changes to unrelated lines)

About

Generates TypeScript from Java - JSON declarations, REST service client

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp