Author Topic: Runtime Javascript Minifying/Obfuscation  (Read 2510 times)

0 Members and 1 Guest are viewing this topic.

Offline Ikkerens

  • LV6 Super Member (Next: 500)
  • ******
  • Posts: 378
  • Rating: +28/-9
  • JavaScript Magician
    • View Profile
    • Walotech
Runtime Javascript Minifying/Obfuscation
« on: September 19, 2011, 03:11:15 pm »
So, recently I've been working on my own webserver, which is now fully functional.
And I came across the part where I wanted my javascript to be minified as soon as the server started up.
This is to save bandwidth blah blah blah...

Anyway, so I've been googling to find a way to do this.
The first thing I came upon was YUI compressor, the downside, this program was meant to be executed using command prompt/terminal, and used to read/save into files.

Absolutely useless in the first case, until I looked into YUI's source.

So, to save alot of users some googling time, or even googlers that manage to get here, here's a way to use YUI compressor on a string, and to result a string.

Preparation
1. Download YUI compressor, and add the source to your classpath as library.
2. Import the following:
Code: (java) [Select]
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.ErrorReporter;

import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

And you should import rhino-1.6R7.jar to your classpath. (Found at /Your YUI folder/lib )

The code
Code: (java) [Select]
String TheJavaScriptString, MinifiedJavaScriptString;
Reader reader = new StringReader(TheJavaScriptString); //Obviously this should point to your string with javascript code
try {
JavaScriptCompressor JSCP = new JavaScriptCompressor(reader, new ErrorReporter() {

public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) {
if (line < 0)
{
System.err.println("\n[WARNING] " + message);
}
else
{
System.err.println("\n[WARNING] " + line + ':' + lineOffset + ':' + message);
}
}

public void error(String message, String sourceName, int line, String lineSource, int lineOffset) {
if (line < 0)
{
System.err.println("\n[ERROR] " + message);
                    }
else
{
                        System.err.println("\n[ERROR] " + line + ':' + lineOffset + ':' + message);
}
}

public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) {
error(message, sourceName, line, lineSource, lineOffset);
  return new EvaluatorException(message);
}
});
Writer out = new StringWriter();
JSCP.compress(out, -1, true, false, false, false);
MinifiedJavaScriptString = out.toString();
} catch (EvaluatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Explanation
At the first line, we "convert" the string to a reader, since YUI only supports types of the reader format.
Originally, YUI gives a FileReader as argument. But this'll do as well.

Since all of the compression magic happens in the JavaScriptCompressor class, we'll call this.
We give it 2 arguments, 1. reader, our string, and 2. an errorreporter. YUI seems to use this to report errors.
You can basically ignore the errorreporter part, since I didn't write it and directly copied it from the YUICompressor class, nothing special here.

After creating the JSCP instance, we'll create a writer (opposite of reader, dôh), but instead of a FileWriter, a StringWriter, since we'll be outputting to a string.
JSCP.compress is YUIcompressor's function to output the code.
This compress function has 6 arguments.
1. the writer, here our stringwriter.
2. the line-break position, not used here: -1
3. munge, do you want the code obfuscated?
4. verbose, output warnings?
5. preserve all semilocons, if false, YUI will check of some semilocons are no longer neccasary.
6. optimisations, do you want YUI to automatically optimize your code?

Then, at last, we let StringWriter output a string, which can then be used for whatever you like...

The End
Well, that's it, if you have any questions feel free to ask them here.

YUI compressor is not owned/produced by me and the license included (LICENSE.txt) should provide you with all the licensing information you need.
« Last Edit: September 19, 2011, 03:12:32 pm by Ikkerens »

Splut for Android [----------]
Paused/halted indefinitely, might be abandoned, our graphic designer quit and the rest of us simply doesn't have the time to work on it...