Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting JavaScript using Java API

I am generating JavaScript code using velocity in java.

For example: I generated JavaScript and got below string:

importClass(java.util.ArrayList); function fun(arg) { if (true){ return true;} else{    return true;}}

Is there any java API that takes this String and formats this JavaScript in below manner:

importClass(java.util.ArrayList);

function fun(arg) { 
   if (true){ 
       return true;
   }
   else{
    return true;
   } 
}
like image 872
Narendra Verma Avatar asked Mar 18 '13 06:03

Narendra Verma


1 Answers

Closure Compiler

You can use Google's Closure Compiler.
It formats, compresses, optimizes, and looks for mistakes in JavaScript code.

For a quick look what it can do, you can try the web service.


Example

For your example string,

importClass(java.util.ArrayList); function fun(arg) { if (true){ return true;} else{    return true;}}

if you just want to format it, use the compile options "Whitespace only" and "Pretty print", which returns:

importClass(java.util.ArrayList);
function fun(arg) {
  if(true) {
    return true
  }else {
    return true
  }
}
;

Anyway, with Closure compiler, you have several options to optimize and/or format your input code (either given as string or file URI) and to either return the optimized/formatted JS as string or save it to a file.

I can really recommend to use the "Simple" optimization mode. For longer Javascripts, it really saves you lots of unneeded bytes. Plus, it speeds up script execution!

For your example string, compile options "Simple" (instead of "Whitespace only") and "Pretty print" return

importClass(java.util.ArrayList);
function fun() {
  return!0
}
;

As you can see, the result of both fun() functions is the same (Boolean true).
However, the second has removed all useless code (by remaining validity!) and will be executed faster.


Download & Reference

Now, the actual compiler is written in Java and is available as a command-line utility to download (Update 2014-07-10: New Downloadlink).

As a second option, you could implement your own wrapper class to communicate with the REST API (as I did for PHP). Doesn't require too much effort/code.

More info is available here:
Google Code Project Page
Getting Started
FAQ: How do I call Closure Compiler from the Java API?
REST API Reference

Hope that helps.

like image 74
eyecatchUp Avatar answered Oct 21 '22 02:10

eyecatchUp