日期:2014-05-17  浏览次数:20874 次

用 YUI Compressor 压缩和混淆 JS 和 CSS

??? 一、简介:

??? 目前开发Web应用Javascript发挥的作用越来越大,相关的Javascript框架也比较多。但是有一个问题,我们开发过程中,所有的JS代码都添加了注释,如使用JsDoc,代码的可读性比较强,同时这样的代码也便于调试。但是在产品环境中,我们希望这些JS代码是压缩和混淆过的,这主要是让 JS代码加载的更快,这也是Google AJAX Libraries API出现的原因。YUI Compressor 是一款由 Yahoo 公司开发的、功能非常强大的 JS、CSS 代码混淆和压缩工具,采用Java开发,目前很多Javascript Framework都使用YUI Compressor进行代码分发。

??? YUI Compressor 官网网址:
???? http://developer.yahoo.com/yui/compressor/

??? YUI Compressor 下载页面:
???? http://yuilibrary.com/downloads/#yuicompressor

??? 二、使用简介:

??? 在命令行下执行 Java 程序,运行 yuicompressor jar 软件包,来完成任务:

??? //压缩JS
??? java -jar yuicompressor-2.4.2.jar --type js --charset utf-8 -v src.js > packed.js

??? //压缩CSS
??? java -jar yuicompressor-2.4.2.jar --type css --charset utf-8 -v src.css > packed.css

??? 三、参考官方英文注释:

??? 3.1 How does the YUI Compressor work?

??? The YUI Compressor is written in Java (requires Java >= 1.4) and relies on Rhino to tokenize the source JavaScript file. It starts by analyzing the source JavaScript file to understand how it is structured. It then prints out the token stream, omitting as many white space characters as possible, and replacing all local symbols by a 1 (or 2, or 3) letter symbol wherever such a substitution is appropriate (in the face of evil features such as eval or with, the YUI Compressor takes a defensive approach by not obfuscating any of the scopes containing the evil statement) The CSS compression algorithm uses a set of finely tuned regular expressions to compress the source CSS file. The YUI Compressor is open-source, so don't hesitate to look at the code to understand exactly how it works.

??? 3.2 Using the YUI Compressor from the command line

??? java -jar yuicompressor-x.y.z.jar

??? Usage: java -jar yuicompressor-x.y.z.jar [options] [input file]

??? Global Options
????? -h, --help??????????????? Displays this information
????? --type <js|css>?????????? Specifies the type of the input file
????? --charset <charset>?????? Read the input file using <charset>
????? --line-break <column>???? Insert a line break after the specified column number
????? -v, --verbose???????????? Display informational messages and warnings
????? -o <file>???????????????? Place the output into <file>. Defaults to stdout.

??? JavaScript Options
????? --nomunge???????????????? Minify only, do not obfuscate
????? --preserve-semi?????????? Preserve all semicolons
????? --disable-optimizations?? Disable all micro optimizations

??? GLOBAL OPTIONS

??? -h, --help
??????? Prints help on how to use the YUI Compressor

??? --line-break
??????? Some source control tools don't like files containing lines longer than,
??????? say 8000 characters. The linebreak optio