
js代码压缩,简称js压缩,英文叫作:javascript minify
js压缩主要有两个作用:
1、压缩代码体积
主要目的是提高代码传输效率。
2、增强代码安全性
可以说,JS压缩也是一种JS混淆加密。
你没听错,JS压缩,可以降底代码可读性。对于既要代码有一定安全性、又要代码体积小的需求而言,JS压缩,是个折中且不错的方案。
为什么压缩代码能具有混淆的效果,下面会讲。
当然是使用工具了。
国内国外,在线的JS压缩小工具很多,一搜一大把,但质量差别很大。
本文只推荐一个,且是国产的、高质量的:JShaman的JSMinify。
众所周知,JShaman是国内JS混淆加密界的知名厂商。所以他们出品的JS压缩工具,品质信的过。
下面简单使用教学:

主要看有哪些功能,再看压缩率。
功能配置:
1、去除未使用的函数。 例,压缩前的代码:
function fun_one(){ console.log(var_one); } function fun_two(){ console.log(var_one); } fun_one();
压缩后:
function fun_one() { console.log(var_one); } fun_one();
2、去除未使用的变量。 例,压缩前的代码:
var var_one = 1; var var_two = 2; function fun_one(){ console.log(var_one); } fun_one();
压缩后:
var var_one = 1; function fun_one() { console.log(var_one); } fun_one();
3、去除空行、无效的“;”号等。
4、优化if、三元运算
例,压缩前的代码:
if(1==1){ console.log("1=1"); } else { console.log("1!=1"); } 2==2?console.log("2=2"):console.log("2!=2");
压缩后:
console.log("1=1"); console.log("2=2");
5、变量使用转化为字符串直接引用
例,压缩前的代码:
var four_one = 4; var four_two; var four_three ="this is four_three"; four_two = 5; console.log(four_one,four_two,four_three,four_three);
压缩后:
var four_two; var four_three = "this is four_three"; four_two = 5; console.log(4, four_two, four_three, four_three);
6、字符串拼接
例,压缩前的代码:
var five_one = 1 + 2 + 3; var five_two = "I am " + "a " + "bird"; console.log(five_one,five_two);
压缩后:
var five_one = 6; var five_two = "I am a bird"; console.log(five_one, five_two);
7、变量名变短。将长变量名变为短变量名。 例,压缩前的代码:
var var_variable_one = 1; var var_variable_two = 2;
压缩后:
var _0_ = 1; var _0_2 = 2;
8、函数名变短。将长函数名变为短函数名。 例,压缩前的代码:
function fun_get_time(){} function fun_set_time(){}
压缩后:
function _f1_(){} function _f2_(){}
9、去除代码中注释。
10、去除代码中的回车、换行,将代码压缩成一行。

配置选项很多,但起用起来很简便,一般用默认配置就行。
再看一下最重要的压缩率:
压缩前:

压缩后:

压缩前体积:674 Bytes 压缩后体积:249 Bytes
压缩效果相当可以。
而且,你看压缩前后代码的可读性是不是也差了许多:
var _v=1;var _v2=2;function _f5(){console.log(_v);}function _f6(){console.log(_v);}_f5();{}console.log("1=1");console.log("2=2");var _f;var _f2="this is four_three";_f=5;console.log(4,_f,_f2,_f2);var _f3=6;var _f4="I am a bird";console.log(_f3,_f4);
JS压缩,真实有用!有需要的朋友,收藏起来吧!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。