標籤:shell 壓縮 javascript
關於javascript代碼檔案的壓縮在之前的文章中提到過(http://blog.csdn.net/u010487568/article/details/19701575),一般來說有三種方式:
- 僅壓縮空白、注釋等字元(最基本方法)
- 壓縮空白、注釋並替換變數名
- 壓縮恐怖、注釋、替換變數名,同時最小化檔案所有的單詞
最近在進一步學習shell,對這個古老的工具越發的感到高效便捷,因此對於這個主題實現了shell版本的最基本方法的實現。主要的策略如下:
- 去除單行注釋
- 去除分行符號和定位字元
- 壓縮多個空格為單個
- 去除多行住處內容
- 將“ (”、“ )”、 “{ ”、“ }”、 “ ; ” 、“ : ” 、“ = ”等字元兩側空格去除
具體實現如下:
##!/usr/bin##########################################################Filename: compreee-js.sh#Author : Oshyn Song#Time : 2014-8-19#Desc : compress the javascript file by basic method########################################################if [ $# -ne 1 ];then echo "Usage: sh $0 js-filename"; exit;fijsfile=$1;echo "Compress $jsfile start ..."; cat -s $jsfile | sed 's!//.*$!!g' | tr -d '\n\t' | tr -s ' ' | sed 's!/\*.*\*/!!g' | sed 's! \?\([+=\!&%$\*\|><{}();,:]\) \?!\1!g' > "compress.${jsfile}";echo "process finished.";
測試如下:原生代碼
;(function(){function __(id){return document.getElementById(id);}function Ajax(options){if (typeof XMLHttpRequest == 'undefined'){XMLHttpRequest = function(){return new ActiveXObject(navigator.userAgent.indexOf('MSIE 5') >= 0 ?'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP');};}..........壓縮後代碼:
;(function(){function __(id){return document.getElementById(id);}function Ajax(options){if(typeof XMLHttpRequest=='undefined'){XMLHttpRequest=function(){return new ActiveXObject(navigator.userAgent.indexOf('MSIE 5')>=0 ?'Microsoft.XMLHTTP':'Msxml2. XMLHTTP');};}.......