YUI Compressor压缩/混淆js脚本示例

YUI Compressor是Yahoo开发的一款js/css压缩工具,它是使用java开发的一个命令行程序,今天我们就用它来测试压缩/混淆js脚本。

一、工具准备

·下载安装JDK:点击下载
·下载解压YUI Compressor:点击下载
·YUI Compressor官方主页:点击查看

二、YUI Compressor语法

引用内容 引用内容
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.
                            Multiple files can be processed using the following
syntax:
                            java -jar yuicompressor.jar -o '.css$:-min.css' *.css
                            java -jar yuicompressor.jar -o '.js$:-min.js' *.js

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

If no input file is specified, it defaults to stdin. In this case, the 'type'
option is required. Otherwise, the 'type' option is required only if the input
file extension is neither 'js' nor 'css'.

三、使用YUI Compressor压缩/混淆js脚本

test.js:
function add(number1,number2)
{
    return number1 + number2;
}

打开CMD窗口,定位到YUI Compressor解压文件夹下的build文件夹,执行如下命令:

java -jar yuicompressor-2.4.6.jar -v --charset gb2312 -o test-min.js test.js

test-min.js:
function add(b,a){return b+a};

四、其他说明

[1].-v参数不是必需的,但建议加上,方便查看一些WARNING信息;
[2].--charset参数不是必需的,但建议加上,YUI Compressor有时并不那么智能;
[3].YUI Compressor不会混淆全局变量名;
[4].养成好的编码习惯,变量尽量一次声明完毕(每个作用域只用一次var),否则会看类似的提示:
[WARNING] Try to use a single 'var' statement per scope.
msg(){var aaa=1; ---> var  <--- bbb=2;alert(aaa+bbb)


评论: 0 | 引用: 0 | 查看次数: 9234
发表评论
登录后再发表评论!