网站首页 文章专栏 JAVA使用YUI压缩CSS/JS
JAVA使用YUI压缩CSS/JS
编辑时间:2018-12-04 16:55:30 作者:田泽 浏览量:514

前言

    JS/CSS文件压缩我们经常会用到,可以在网上找在线压缩或者本地直接使用,我这里使用的是yahoo开源组件YUI Compressor。
首先介绍一下YUI Compressor,它是一个用来压缩JS和CSS文件的工具,采用Java开发。JavaScript和CSS缩小的目标是始终保持代码的操作质量,同时减少其整体字节占用,YUI Compressor设计为100%安全的JavaScript分选程序,并且比大多数其他工具具有更高的压缩比。与JSMin相比,YUI Library 的测试节省了20%以上(HTTP压缩后为10%)。YUI Compressor还可以通过使用Isaac Schlueter的基于正则表达式的CSS minifier 的端口来压缩CSS文件。,下面为大家分享一下使用yuicompressor压缩js文件和压缩css文件。
    压缩文件可以减小文件大小,JS文件会默认去掉分号,注释,会将一些参数名改为a,b,c等,减低可读性

YUI Compressor官网:http://yui.github.io/yuicompressor/

jar包下载:链接:https://pan.baidu.com/s/1cKM5pxgMduxBIdJRGXX9vg 提取码:q2s2 

开始使用

    js代码:

/**
* 验证密码和账户
*/
function validate2(username, password) {
if (username != "zhangsan") {
alert("userName is error:" + c)
}
if (password != "123456") {
alert("password is error:" + d)
}
};

    进行压缩:

D:>java -jar yuicompressor-2.4.7.jar index.js -v -o index-min.js --charset UTF-8

   参数说明:

index.js  需要压缩的源文件
-v -o 显示信息与指定输出文件名字
index-min.js 压缩后的文件
--charset 指定编码格式

     压缩后文件:

function validate2(b,a){if(b!="zhangsan"){alert("userName is error:"+c)}if(a!="123456"){alert("password is error:"+d)}};

压缩后文件改变了参数名,去掉了分号。

    不去分号:

D:>java -jar yuicompressor-2.4.7.jar index.js -v --preserve-semi -o index-min.js --charset UTF-8

    压缩css:

D:>java -jar yuicompressor-2.4.7.jar index.css -v -o index1-min.css --charset UTF-8

JAVA代码

    实现原理 通过java执行cmd命令,for循环遍历文件夹下js/css文件。可实现批量压缩

package zdComputerTest;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
* 通过yuicompressor压缩JS|CSS文件工具类
* @author Administrator
*
*/
public class CompressUtils {
private static final String encoding = "utf-8";
private static final String[] suffixArray = { ".js", ".css" };

public static void main(String[] args) {
String yuiPath = "D:/yuicompressor-2.4.7.jar";
String filePath = "D:/js";

compressFile(yuiPath, filePath);
}

/**
* 压缩指定文件夹下所有的js/css
*
* @param yuiPath
* yuicompressor-2.4.7.jar文件路径
* @param filePath
* 要压缩的文件夹路径
*/
public static void compressFile(String yuiPath, String filePath) {
File file = new File(filePath);
List<String> commondList = new ArrayList<String>();
initCommondList(yuiPath, commondList, file);
excuteCompress(commondList);
}

/**
* 执行压缩命令
* @param commondList
*/
private static void excuteCompress(List<String> commondList) {
Runtime runTime = Runtime.getRuntime();
Date startTime = new Date();
Long count = 0L;
for (String cmd : commondList) {
try {
System.out.println(cmd);
runTime.exec(cmd);
count++;
} catch (IOException e) {
e.printStackTrace();
}
}
Date endTime = new Date();
Long cost = endTime.getTime() - startTime.getTime();
System.out.println("压缩完成,耗时:" + cost + "ms,共压缩文件个数:" + count);
}

/**
* 初始化压缩命令
* @param yuiPath
* @param commondList
* @param file
*/
private static void initCommondList(String yuiPath,
List<String> commondList, File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
// 如果某个文件夹是空文件夹,则跳过
if (files == null) {
return;
}
for (File f : files) {
initCommondList(yuiPath, commondList, f);
}
} else {
String fileName = file.getName();
String suffix = fileName.substring(fileName.lastIndexOf("."),
fileName.length());

List<String> suffixList = Arrays.asList(suffixArray);
if (suffixList.contains(suffix)
&& !fileName.endsWith("-min" + suffix)) {
StringBuffer sb = new StringBuffer();
sb.append("java -jar ");
sb.append(yuiPath);
sb.append(" --type ");
sb.append(suffix.substring(suffix.indexOf(".") + 1));
sb.append(" --charset ");
sb.append(encoding).append(" ");
sb.append(file.getPath()).append(" ");
sb.append("-o").append(" ");
sb.append(file.getPath().replace(suffix, "-min" + suffix));

commondList.add(sb.toString());
}

}
}
}


    YUI参数使用帮助:

java -jar yuicompressor-x.y.z.jar
Usage: java -jar yuicompressor-x.y.z.jar [options] [input file]

Global Options
-h, --help Displays this information
--type <js|css> Specifies the type of the input file
--charset <charset> Read the input file using <charset>
--line-break <column> Insert a line break after the specified column number
-v, --verbose Display informational messages and warnings
-o <file> Place the output into <file> or a file pattern.
Defaults to stdout.

JavaScript Options
--nomunge Minify only, do not obfuscate
--preserve-semi Preserve all semicolons
--disable-optimizations Disable all micro optimizations

GLOBAL OPTIONS

-h, --help
Prints help on how to use the YUI Compressor

--line-break
Some source control tools don’t like files containing lines longer than,
say 8000 characters. The linebreak option is used in that case to split
long lines after a specific column. It can also be used to make the code
more readable, easier to debug (especially with the MS Script Debugger)
Specify 0 to get a line break after each semi-colon in JavaScript, and
after each rule in CSS.

--type js|css
The type of compressor (JavaScript or CSS) is chosen based on the
extension of the input file name (.js or .css) This option is required
if no input file has been specified. Otherwise, this option is only
required if the input file extension is neither ’js’ nor ’css’.

--charset character-set
If a supported character set is specified, the YUI Compressor will use it
to read the input file. Otherwise, it will assume that the platform’s
default character set is being used. The output file is encoded using
the same character set.

-o outfile

Place output in file outfile. If not specified, the YUI Compressor will
default to the standard output, which you can redirect to a file.
Supports a filter syntax for expressing the output pattern when there are
multiple input files. ex:
java -jar yuicompressor.jar -o ’.css$:-min.css’ *.css
... will minify all .css files and save them as -min.css

-v, --verbose
Display informational messages and warnings.

JAVASCRIPT ONLY OPTIONS

--nomunge
Minify only. Do not obfuscate local symbols.

--preserve-semi
Preserve unnecessary semicolons (such as right before a ’}’) This option
is useful when compressed code has to be run through JSLint (which is the
case of YUI for example)

--disable-optimizations
Disable all the built-in micro optimizations.



支付宝打赏 微信打赏

您的支持是我最大的动力。

吐槽区