---
title: "JS和CSS压缩器，以及nginx的concat模块"
author: "suflow"
date: "2012-08-21T11:46:01Z"
tags: []
categories: ["开源软件"]
slug: "js-css-nginx-concat"
draft: false
lastmod: "2012-08-29T13:34:44Z"
id: 1643786
url: "https://suflow.iteye.com/blog/1643786"
---

## **一、一个是js 和 css的文件压缩器**

其实是两个工具，我把它们合在一起  
1\. 首先是，老牌的 YUI Compressor 。  
很简单 ， [http://developer.yahoo.com/yui/compressor/](http://developer.yahoo.com/yui/compressor/)  只要下载一个jar包，就可以了  
使用方式：

 

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

 

具体的 options 可以通过 java -jar yuicompressor-x.y.z.jar -h 查看,  
这里最好通过参数指定一下编码 --charset utf-8，默认会采用系统编码

2\. 然后是，Google的 Closure Compiler，它是专门正对js的 编译器（不仅仅是压缩）  
官方地址： [https://developers.google.com/closure/compiler/](https://developers.google.com/closure/compiler/)  
使用方式：

`java -jar compiler.jar --js [INPUT_FILE] --js_output_file [OUTPUT_FILE]`

默认编码是 输入文件为utf-8,输出为ASCII

它有三种编译的等级用以下参数指定：

--compilation\_level \[WHITESPACE\_ONLY | SIMPLE\_OPTIMIZATIONS | ADVANCED\_OPTIMIZATIONS]

默认采用SIMPLE\_OPTIMIZATIONS， 请谨慎使用高级模式（ADVANCED\_OPTIMIZATIONS）

测试了一下发现Closure Compiler的 压缩率会比YUI Compressor 高一些（大概将近10%）  
所以，我一般用Closure Compiler压 缩js，用YUI Compressor压缩 css，写了一个简单的脚本

 

```
#!/bin/bash</p>
 
# compress 'js' or 'css' files</p>
 
if [ $# -eq 0 ]; then
    echo 'Usage: compressor.sh [input file]'
    exit 1
fi
 
INPUT_FILE=${!#}
echo "Input file is: $INPUT_FILE"
echo "Start compress ... "
 
SNAME=${INPUT_FILE%.*}
SEXT=${INPUT_FILE##*.}
OUTPUT_FILE=${SNAME}.min.${SEXT}
if [ $SEXT = 'js' -o $SEXT = 'JS' ];then
    echo "Run Closure-Compiler ..."
    java -jar compiler.jar --js $INPUT_FILE --js_output_file $OUTPUT_FILE
else
    echo "Run YUI-Compressor ..."
    java -jar yuicompressor-2.4.7.jar $INPUT_FILE -o $OUTPUT_FILE --charset utf-8
fi</p>
 
echo "Compress successful."
echo "Output file is: $OUTPUT_FILE"
```

 

 

## **二、nginx的concat组件**

大家应该看到过这样的链接吧  
[http://{domain}//js/??zepto.js,base.js,index.js](http://huskarl.3322.org/base/utils/server/pg/copy/?%3Fcom.js%2Cbase.js%2Cindex.js)  
原本是三个链接，通过nginx的concat组件，可以合并这些简单的资源链接，减少http请求。  
1\. 先下载concat：  
svn co [http://code.taobao.org/svn/nginx\_concat\_module/trunk](http://code.taobao.org/svn/nginx_concat_module/trunk) **nginx\_concat\_module**

2\. 再下载nginx，并指定concat的路径（上面下载的目录） 安装

./configure --prefix=/opt/nginx --add-module=$MYDIR/nginx\_concat\_module  
 make  
sudo make install

3\. 最后配置nginx

`location / {`

`root   html;`

`index  index.html index.htm;`

`concat  on;#开关`

`}`