写js的程序猿,应该都用过UglifyJS吧?
我们将深度剖析UglifyJS。
UglifyJS
UglifyJS是一个js压缩工具,已在GitHub开源。
下载方式
npm install uglify-js
或者在线demo
UglifyJS原理
UglifyJS压缩js的原理有以下几点:
1.压缩变量
例:global→e,factory→t
2.压缩运算和空格
压缩前:
if(typeof set === "object"){
set += root.x;
} else {
set = set.concat([]);
}
压缩后:
"object"==typeof set?set+=root.x:set=set.concat([])
3.石粒示例:
Time.js(原创)
压缩前:
/*!
* Time JavaScript Library v3.6.3
* Author: Chi Zeyu.
* Date: 2022-12-20T21:28Z
*/
;( function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error();
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
} ( typeof window !== "undefined" ? window : this, function (config) {
if (typeof config === "object") {
if (config.type == "time") { //time
function formatDate(format) {
date = new Date()
const that = new Date(date);
var table = { // create timetable
'M+': that.getMonth() + 1, // months
'd+': that.getDate(), // dates
'h+': that.getHours(), // hours
'm+': that.getMinutes(), // minutes
's+': that.getSeconds(), // seconds
};
if (/(y+)/.test(format)) { //regex
format = format.replace(RegExp.$1, (that.getFullYear() + '')
.substr(4 - RegExp.$1.length));
}
for (var str in table) {
if (new RegExp('(' + str + ')')
.test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (table[str]) : (('00' + table[str])
.substr(('' + table[str])
.length))); //replace
}
}
return format;
}
return formatDate(config.format)
} else if (config.type == "timestamp") { //timestamp
return new Date()
.getTime();
}
} else {
throw new Error("Param 'config' is not an object"); //error
}
} ));
压缩后:
!function(e,t){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw Error()
return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e){function t(e){date=new Date
const t=new Date(date)
var o={"M+":t.getMonth()+1,"d+":t.getDate(),"h+":t.getHours(),"m+":t.getMinutes(),"s+":t.getSeconds()};/(y+)/.test(e)&&(e=e.replace(RegExp.$1,(t.getFullYear()+"").substr(4-RegExp.$1.length)))
for(var n in o)RegExp("("+n+")").test(e)&&(e=e.replace(RegExp.$1,1===RegExp.$1.length?o[n]:("00"+o[n]).substr((""+o[n]).length)))
return e}if("object"!=typeof e)throw Error("Param 'config' is not an object")
return"time"==e.type?t(e.format):"timestamp"==e.type?(new Date).getTime():void 0})
怎么样,牛X吧?
还有更牛X的!
看看压缩前的jQuery和压缩后的jQuery,你就知道UglifyJS有多牛X了!
好了,不说了,拜拜