---
title: "放弃繁琐的配置！直接使用UglifyJS批量压缩目录下所有JS文件"
author: "renzhen"
date: "2012-10-18T08:47:50Z"
tags: []
categories: ["编程语言"]
slug: "uglifyjs-js"
draft: false
lastmod: "2012-10-18T08:45:45Z"
id: 1699844
url: "https://renzhen.iteye.com/blog/1699844"
---

JS代码压缩是一种十分常见的前端优化的手段，对于大量使用JS的Web应用，代码压缩可以是极大的减少代码的大小，加快传输效率，提高浏览的体验。
     而在所有的JS压缩工具中，UglifyJS在不改变JS语义前提下可以提供最好的压缩率，其优异的性能而广为称颂，而与它性能相对应的是复杂的运行环境，你需要安装nodejs、然后使用npm安装UglifyJS类库，最后还要编写js...My God，我只是想压缩一下代码而已。
     如果你和我一样既希望享受UglifyJS高效率，又苦恼于复杂繁琐的配置，你可以尝试如下方法。在网上有很多在线压缩JS代码的站点，支持UglifyJS也不少，但是只能手动操作，无法批量处理，实用性实在不怎么高。但是如果有站点提供REST API给程序调用，那结果就不同了。
     对于UglifyJS在<http://marijnhaverbeke.nl/uglifyjs>中就有一个可供程序调用的HTTP API：

> 
> UglifyJS compression can be used as an HTTP service by sending a POST or GET request to this URL, with any of the parameters listed below either embedded in the URL, or in an application/x-www-form-urlencoded request body. The response body will contain the compressed code in case of a successful request, or an error message when returning an error HTTP status code.
> 
> code_url
> A URL pointing at a JavaScript file to compress. Only the http: and https: protocols are supported. Invalid or errorring URLs will be ignored. This parameter can be given multiple times to concatenate the scripts at those locations together.
> js_code
> JavaScript code passed directly inside the request. Both this parameter and code_url can be given, in which case the code passed in js_code will end up after the code from URLs.
> utf8
> Defaults to off, can be passed (with any value) to allow non-ascii characters to appear in the output.
> download
> When given, this should contain a filename. The server will add a Content-Disposition header to the response, which causes typical browsers to download the response under the given filename.
> 

  通过这个API，就可以使用任意的编程语言进行文件夹批量压缩JS的操作了。下面是我用PHP写的调用API批量压缩的小脚本：

```php

<?php
set_time_limit(0);
$fromdir="E:\\wamp\\www\\wopop20\\script";
$todir="D:\\cscript";
compressDir($fromdir,$todir);
echo "success";
function compressDir($fromdir,$todir){
	if ($handle = opendir($fromdir)) {
			if(!is_dir($todir)) mkdir($todir, 0777, true);
			while (false !== ($file = readdir($handle))) {
					if ($file != "." && $file != "..") {
						$absolutefilename=$fromdir."\\".$file;
						if(is_file($absolutefilename)&&preg_match('/\.js$/',$file)){
//							echo $absolutefilename,'<br>';
							$str=compressJS($absolutefilename);
							file_put_contents($todir."\\".$file, $str);
						}elseif(is_dir($absolutefilename)){
							compressDir($absolutefilename,$todir."\\".$file);
						}
					}
			}
			closedir($handle);
	}

}

function compressJS($filename){
	$url="http://marijnhaverbeke.nl/uglifyjs";
	$filecontent=file_get_contents($filename);
	static $ch;
//	echo $filecontent;
	if(empty($ch)){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HTTPGET, false);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	}

	$data=array('js_code'=>$filecontent,'utf8'=>'1');
	curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
	
	

	$compresstext=curl_exec($ch);
//	curl_close($ch);
	if(!empty($compresstext)){
		return $compresstext;
	}
	echo "compress {$filename} failed";
	return false;
}
?>

```