问题
I use YUI Compressor for years to minify and obfuscate JS files. But now I need to obfuscate and minify dynamically generated JavaScript code on the server. So the main difference here is that there will not be JS files that should be obfuscated but requests to the server (Java) which should generate portions of JS code and return them already minified and obfuscated.
YUI Compressor does not give the possibility to do that. I watched in the sources and have already figured out what methods should be overridden to make it work. I would not like to do this (but will have to in case there is no other way).
So are there any other Java libraries allowing to minify and obfuscate JavaScript strings directly from Java code?
回答1:
Plan a)
Use the YUI not as a command line tool, but as a Java library and call it in your code.
The JavaScriptCompressor accepts a Reader descendant (e.g. InputFileReader).
JavaScriptCompressor compressor = new JavaScriptCompressor(in, new YuiCompressorErrorReporter());
You can actually get your raw JavaScript and convert it to a Stream, e.g. How do I convert a String to an InputStream in Java?
A full example of integration is here:
http://blog.teamextension.com/yui-compressor-in-java-246
Plan b)
Note that you could simply save the generated javascript into the filesystem, and call the command line Yui from Java. Then read the minified file from the filesystem, and that's it, you have a minified JS.
来源:https://stackoverflow.com/questions/14003126/minify-and-obfuscate-javascript-code-in-java