简体   繁体   中英

Java Library to generate JavaScript Code

I need to generate JavaScript (ECMAScript) code from inside a Java program. For that, I am looking for something like JavaPoet , but producing JavaScript as output.

I cannot use one of these transpilers that translates another language into JavaScript (eg GWT is not the answer) nor a tool that generates JavaScript from a syntax tree (only when there is a library that helps building that syntax tree ...).

Something like the already mentioned JavaPoet would be the answer because it has a very small footprint both in memory usage and in code size.

Target for the resulting JavaScript code is Java/JSR 223 (Nashorn), if this would be relevant.

To specify the requirements: JavaPoet uses this code

MethodSpec main = MethodSpec.methodBuilder("main")
    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
    .returns(void.class)
    .addParameter(String[].class, "args")
    .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
    .build();

TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
    .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
    .addMethod(main)
    .build();

JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
    .build();
javaFile.writeTo(System.out);

to create this Java code

package com.example.helloworld;

public final class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, JavaPoet!");
  }
}

(I've copied the sample from the JavaPoet project web site.)

I would like to have something similar that creates JavaScript code instead.

To my current knowledge, StringBuilder is in fact closest to this requirement. First generating Java to transform it to JavaScript should work, but looks really odd to me - and is all, but not really lightweight. Same as first generate Kotlin or Ceylon code and then transforming it to JavaScript.

I know you don't want a transpiler, but since it seems that there is no javascript generator for what you want, probably a light-weight java-js transpiler could do the job.

Try to produce some java with javapoet as you mentioned and then make the output pass through the jsweet transpiler, there is an online sandbox that you can use to see the output before deciding whether it is the best option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM