JavaScript代碼優(yōu)化新工具UglifyJS
jQuery 1.5 發(fā)布的時候 john resig 大神說所用的代碼優(yōu)化程序從Google Closure切換到UglifyJS,新工具的壓縮效果非常令人滿意。 UglifyJS 是一個服務(wù)端node.js的壓縮程序。我測試了一下壓縮率確實比較高。 所以值得寫篇文章推薦下。
你也可以嘗試一下在線版的Uglifyjs: http://sweet.fengyin.name/
如果你對 uglifyjs 有興趣可以按照以下安裝方式進(jìn)行安裝。
1. 安裝 node.js 環(huán)境
2. 進(jìn)入 https://github.com/mishoo/UglifyJS 右上角 “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/ 目錄。執(zhí)行 ./uglifyjs /你的js路徑/xx.js 如果安裝成功會把你的壓縮代碼直接顯示在命令行。你可以通過 ./uglifyjs 1.js 2.js 把壓縮后的代碼保存到 2.js
至此 uglifyjs 安裝完成,我還寫了一個PHP類。可以調(diào)用 uglifyjs 進(jìn)行壓縮
- /*
- # code by https://fengyin.name
- # DEMO http://sweet.fengyin.name/
- # Dual licensed under the MIT
- */
- $uglifyjs = new uglifyjs(array(
- 'node_home'=>'/usr/local/bin/node',
- 'uglifyjs_path'=>'/usr/UglifyJS/bin/uglifyjs', //uglifyjs壓縮工具的路徑。
- // -------- 附加的參數(shù) --------- //
- 'prefix'=>'-b', //輸入的參數(shù) -b 是格式化 不輸入為壓縮,還有更多請參考命令用法。
- 'append'=>''//保存文件,如果為空就是直接在命令行輸出結(jié)果。
- ));
- $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 [ 選項... ] [ 文件 ]
文件參數(shù)應(yīng)該放在選項后面,uglifyjs 會讀取文件中的javascript代碼進(jìn)行處理。
如果你不指定輸出的文件名,那么他會把處理后的內(nèi)容輸出到命令行中。
例: uglifyjs 1.js 2.js 會創(chuàng)建一個 2.js 文件把 1.js處理完畢的內(nèi)容輸入到這里
例: uglifyjs 1.js 會讀取1.js內(nèi)容,并把結(jié)果輸出到命令行中。
支持的選項:
-b or --beautify — 參數(shù) -b 或者 --beautify 用于美化(格式化)代碼。美化之前會壓縮代碼(未驗證。)
-i N or --indent N — 縮進(jìn)級別空格數(shù)
例:uglifyjs -b 1.js 2.js 會把1.js的內(nèi)容格式后輸出到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()(可以使各種優(yōu)化之后的代碼更小,更具有可讀性。)
-mt or --mangle-toplevel — mangle names in the toplevel scope too (by default we don’t do this).
--no-seqs — 當(dāng)ast_squeeze()被調(diào)用的時候(除非你添加了--no-squeeze 參數(shù)才不會被調(diào)用)它將減少在一個代碼塊中重復(fù)聲明的行。例如:“a = 10; b = 20; foo();”將被重寫為“a=10,b=20,foo();”。在各種場合,這將允許我們丟棄代碼塊中的括號(在一些語句塊變成一個獨立的聲明行之后)。這是默認(rèn)的,因為經(jīng)我們測試,它似乎更安全并且能節(jié)省幾百bytes,但加上--no-seqs 后將被禁止。
--no-dead-code — 默認(rèn)情況下,UglifyJS將會刪除代碼中明顯無法訪問的語句(如 return , throw , break 或者continue語句 ,以及一些不是函數(shù)/變量的的聲明)。通過這個選項可以禁用掉這個優(yōu)化功能。
-nc or --no-copyright — 默認(rèn)情況下,uglifyjs將在生成的代碼中保留初始的一些標(biāo)記(假設(shè)版權(quán)信息等)。如果你設(shè)置這個參數(shù)將被禁止。
-o filename or --output filename — 將結(jié)果輸出到一個指定文件名的文件中。如果沒有這個參數(shù),結(jié)果將會被輸出到命令行
-
-overwrite — 如果代碼是從一個文件中讀取的(不是直接標(biāo)準(zhǔn)輸入的)并且使用了--overwrite參數(shù),那么結(jié)果也將會被寫進(jìn)相同的文件中去。
--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輸出的抽象語法樹,這些參數(shù)會在你進(jìn)行調(diào)試或?qū)W習(xí)內(nèi)部組件時很有用。
-v or --verbose — output some notes on STDERR (for now just how long each operation takes).
-v or --verbose — output 一些標(biāo)準(zhǔn)錯誤提示(顯示每一次花費多久)
--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.
當(dāng)你發(fā)現(xiàn)BUG時你可以增加一個中斷點用來對還沒有徹底的測試的代碼進(jìn)行優(yōu)化,你可以使用這個選項來生成一個測試用例。
--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() 這種用法 也是可行的,但是存在一些人為的不安全的情況,這事也需要添加一些優(yōu)化比如: 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字節(jié)的時候你要增加一行,我有發(fā)現(xiàn)過在火狐和chorme下檔代碼一行超過670K的時候它會發(fā)出報警聲。通過–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 所以這個選項允許你去排除一些關(guān)鍵字。
【編輯推薦】