JAVA使用YUI壓縮CSS/JS


前言

    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文件。可實現批量壓縮

  1 import java.io.File;
  2 import java.io.IOException;
  3 import java.util.ArrayList;
  4 import java.util.Arrays;
  5 import java.util.Date;
  6 import java.util.List;
  7 
  8 /**
  9  * 通過yuicompressor壓縮JS|CSS文件工具類
 10  * @author Administrator
 11  *
 12  */
 13 public class CompressUtils {
 14     private static final String encoding = "utf-8";
 15     private static final String[] suffixArray = { ".js", ".css" };
 16 
 17     public static void main(String[] args) {
 18         String yuiPath = "D:/yuicompressor-2.4.7.jar";
 19         String filePath = "D:/js";
 20 
 21         compressFile(yuiPath, filePath);
 22     }
 23 
 24     /**
 25      * 壓縮指定文件夾下所有的js/css
 26      * 
 27      * @param yuiPath
 28      *            yuicompressor-2.4.7.jar文件路徑
 29      * @param filePath
 30      *            要壓縮的文件夾路徑
 31      */
 32     public static void compressFile(String yuiPath, String filePath) {
 33         File file = new File(filePath);
 34         List<String> commondList = new ArrayList<String>();
 35         initCommondList(yuiPath, commondList, file);
 36         excuteCompress(commondList);
 37     }
 38 
 39     /**
 40      * 執行壓縮命令
 41      * @param commondList
 42      */
 43     private static void excuteCompress(List<String> commondList) {
 44         Runtime runTime = Runtime.getRuntime();
 45         Date startTime = new Date();
 46         Long count = 0L;
 47         for (String cmd : commondList) {
 48             try {
 49                 System.out.println(cmd);
 50                 runTime.exec(cmd);
 51                 count++;
 52             } catch (IOException e) {
 53                 e.printStackTrace();
 54             }
 55         }
 56         Date endTime = new Date();
 57         Long cost = endTime.getTime() - startTime.getTime();
 58         System.out.println("壓縮完成,耗時:" + cost + "ms,共壓縮文件個數:" + count);
 59     }
 60 
 61     /**
 62      * 初始化壓縮命令
 63      * @param yuiPath
 64      * @param commondList
 65      * @param file
 66      */
 67     private static void initCommondList(String yuiPath,
 68             List<String> commondList, File file) {
 69         if (file.isDirectory()) {
 70             File[] files = file.listFiles();
 71             // 如果某個文件夾是空文件夾,則跳過
 72             if (files == null) {
 73                 return;
 74             }
 75             for (File f : files) {
 76                 initCommondList(yuiPath, commondList, f);
 77             }
 78         } else {
 79             String fileName = file.getName();
 80             String suffix = fileName.substring(fileName.lastIndexOf("."),
 81                     fileName.length());
 82 
 83             List<String> suffixList = Arrays.asList(suffixArray);
 84             if (suffixList.contains(suffix)
 85                     && !fileName.endsWith("-min" + suffix)) {
 86                 StringBuffer sb = new StringBuffer();
 87                 sb.append("java -jar ");
 88                 sb.append(yuiPath);
 89                 sb.append(" --type ");
 90                 sb.append(suffix.substring(suffix.indexOf(".") + 1));
 91                 sb.append(" --charset ");
 92                 sb.append(encoding).append(" ");
 93                 sb.append(file.getPath()).append(" ");
 94                 sb.append("-o").append(" ");
 95                 sb.append(file.getPath().replace(suffix, "-min" + suffix));
 96 
 97                 commondList.add(sb.toString());
 98             }
 99 
100         }
101     }
102 }

 

 

    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.

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM