Minify and obfuscate JavaScript code in Java

情到浓时终转凉″ 提交于 2021-01-27 12:44:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!