JavaScript代码优化新工具UglifyJS

 jQuery 1.5 发布的时候 john resig 大神说所用的代码优化程序从Google Closure切换到UglifyJS,新工具的压缩效果非常令人满意。 UglifyJS 是一个服务端node.js的压缩程序。我测试了一下压缩率确实比较高。 所以值得写篇文章推荐下。

  你也可以尝试一下在线版的Uglifyjs:

  如果你对 uglifyjs 有兴趣可以按照以下安装方式进行安装。

  1. 安装 node.js 环境

  2. 进入 右上角 “Download” ZIP下载整个包。

  3. 解压打开 UglifyJS/bin/uglifyjs

  4. 找到

 global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");  
  var fs = require("fs");  
  var uglify = require("uglify-js"), // symlink ~/.node_libraries/uglify-js.js to ../uglify-js.js  
      jsp = uglify.parser,  
      pro = uglify.uglify;  

  替换为

global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");  
  var fs = require("fs");  
  require.paths.unshift(__dirname + "/../");  
  var uglify = require("index"),  
  jsp = uglify.parser,  
  pro = uglify.uglify; 

 

  5. cd 命令到 UglifyJS/bin/ 目录。执行 ./uglifyjs /你的js路径/xx.js 如果安装成功会把你的压缩代码直接显示在命令行。你可以通过 ./uglifyjs 1.js 2.js 把压缩后的代码保存到 2.js

  至此 uglifyjs 安装完成,我还写了一个PHP类。可以调用 uglifyjs 进行压缩

/*  
  # code by  
  # DEMO  
  # Dual licensed under the MIT  
  */ 
   
  $uglifyjs = new uglifyjs(array(  
   'node_home'=>'/usr/local/bin/node',  
   'uglifyjs_path'=>'/usr/UglifyJS/bin/uglifyjs', //uglifyjs压缩工具的路径。  
   // -------- 附加的参数 --------- //  
   'prefix'=>'-b', //输入的参数 -b 是格式化 不输入为压缩,还有更多请参考命令用法。  
   'append'=>''//保存文件,如果为空就是直接在命令行输出结果。  
   ));  
  $results =  $uglifyjs ->compress($_FILES['file']['tmp_name']);  
   
   
  class uglifyjs{  
          function __construct($options = array()) {  
              $this->options = $options;  
          }  
         function args($option) {  
              return $option['node_home'].' '.$option['uglifyjs_path'].' 
  '.$option['prefix'].' '.$option['file'].' '.$option['append'];  
       
          }  
          function exec($cmd) {  
              exec($cmd.' 2>&1',$out, $status);  
              return json_encode(array(  
              'shell' => $cmd,  
                  'output' => implode("\n",$out),  
                  'status' => $status  
              ));  
          }  
          function compress($file) {  
              $this->options['file'] = $file;  
              return $this->exec($this->args($this->options));  
          }  
      }  
  ?> 

 

  文章最后附上 uglifyjs 的命令行中文说明

  使用:

  这是一个脚本助手(工具)-bin/uglifyjs-使用这个库可以用来把一个脚本压缩到最小。

  简介:

  uglifyjs [ 选项... ] [ 文件 ]

  文件参数应该放在选项后面,uglifyjs 会读取文件中的javascript代码进行处理。

  如果你不指定输出的文件名,那么他会把处理后的内容输出到命令行中。

  例: uglifyjs 1.js 2.js 会创建一个 2.js 文件把 1.js处理完毕的内容输入到这里

  例: uglifyjs 1.js 会读取1.js内容,并把结果输出到命令行中。

  支持的选项:

  -b or --beautify — 参数 -b 或者 --beautify 用于美化(格式化)代码。美化之前会压缩代码(未验证。)

  -i N or --indent N — 缩进级别空格数

  例:uglifyjs -b 1.js 2.js 会把1.js的内容格式后输出到2.js

  -q or --quote-keys — quote keys in literal objects (by default, only keys that cannot be identifier names will be quotes).

  -nm or --no-mangle — 变量名不缩短,意味着不会把代码的变量名缩短为 abcdefg

  -ns or --no-squeeze — 不使用ast_squeeze()(可以使各种优化之后的代码更小,更具有可读性。)

  -mt or --mangle-toplevel — mangle names in the toplevel scope too (by default we don’t do this).

  --no-seqs — 当ast_squeeze()被调用的时候(除非你添加了--no-squeeze 参数才不会被调用)它将减少在一个代码块中重复声明的行。例如:“a = 10; b = 20; foo();”将被重写为“a=10,b=20,foo();”。在各种场合,这将允许我们丢弃代码块中的括号(在一些语句块变成一个独立的声明行之后)。这是默认的,因为经我们测试,它似乎更安全并且能节省几百bytes,但加上--no-seqs 后将被禁止。

  --no-dead-code — 默认情况下,UglifyJS将会删除代码中明显无法访问的语句(如 return , throw , break 或者continue语句 ,以及一些不是函数/变量的的声明)。通过这个选项可以禁用掉这个优化功能。

  -nc or --no-copyright — 默认情况下,uglifyjs将在生成的代码中保留初始的一些标记(假设版权信息等)。如果你设置这个参数将被禁止。

  -o filename or --output filename — 将结果输出到一个指定文件名的文件中。如果没有这个参数,结果将会被输出到命令行

  -

  -overwrite — 如果代码是从一个文件中读取的(不是直接标准输入的)并且使用了--overwrite参数,那么结果也将会被写进相同的文件中去。

  --ast — pass this if you want to get the Abstract Syntax Tree instead of JavaScript as output. Useful for debugging or learning more about the internals.

  --ast — pass 如果你要获取一个用来取代javascript输出的抽象语法树,这些参数会在你进行调试或学习内部组件时很有用。

  -v or --verbose — output some notes on STDERR (for now just how long each operation takes).

  -v or --verbose — output 一些标准错误提示(显示每一次花费多久)

  --extra — enable additional optimizations that have not yet been extensively tested. These might, or might not, break your code. If you find a bug using this option, please report a test case.

  当你发现BUG时你可以增加一个中断点用来对还没有彻底的测试的代码进行优化,你可以使用这个选项来生成一个测试用例。

  --extra — enable

  --unsafe — enable other additional optimizations that are known to be unsafe in some contrived situations, but could still be generally useful. For now only this:

  foo.toString() ==> foo+””

  想foo.toString() 这种用法 也是可行的,但是存在一些人為的不安全的情况,这事也需要添加一些优化比如: foo+””

  --max-line-len (default 32K characters) — add a newline after around 32K characters. I’ve seen both FF and Chrome croak when all the code was on a single line of around 670K. Pass –max-line-len 0 to disable this safety feature.

  在超过大概32K字节的时候你要增加一行,我有发现过在火狐和chorme下档代码一行超过670K的时候它会发出报警声。通过–max-line-len 0 去静止这个安全属性

  --reserved-names — some libraries rely on certain names to be used, as pointed out in issue #92 and #81, so this option allow you to exclude such names from the mangler. For example, to keep names require and $super intact you’d specify –reserved-names “require,$super”.

  --reserved-names — 些类库会依赖于特定的名称去使用,比如:#92 和#81 所以这个选项允许你去排除一些关键字。

posted on 2014-07-02 14:33  星空夜夏梦  阅读(772)  评论(0编辑  收藏  举报

导航