您的位置:首页 > Web前端 > JavaScript

使用Ant命令压缩JavaScript文件

2013-08-14 13:39 246 查看
压缩JavaScript文件可以减少代码尺寸,保护源代码,节省网络带宽,加快页面打开速度,甚至优化JS代码。Yahoo有一个压缩JS的工具叫做YUI compressor, Google也有一个工具叫Google Closure Compilerlifesinger的blog上有一个Slide对它们做了详细的比较。

关于如何使用YUI compressor和Google Closure Compiler, 请参照相应的官方文档。本篇主要是将压缩命令整理成build.xml,然后通过ant命令来执行。下面是项目的build配置文件:

<?xml version="1.0" encoding="utf-8"?>
<project name="Javascript compress project" basedir=".">

<property name="COMPRESSED_HOME" value="${basedir}/compressed"/>

<!--compress js file by YUI compressor-->
<target name="yui-compress">
<property name="yui.compress" value="${basedir}/lib/yuicompressor-2.4.2.jar" />
<apply executable="java" parallel="false" verbose="true" dest="${COMPRESSED_HOME}" taskname="js.compile">
<fileset dir="${basedir}">
<include name="*.js"/>
</fileset>
<arg line="-jar"/>
<arg path="${yui.compress}" />
<arg line="--type js --charset UTF-8 -o" />
<mapper type="glob" from="*.js" to="*-yui-min.js" />
<targetfile />
</apply>
</target>

<!--compress js file by Google Closure Compiler-->
<target name="google-compress">
<property name="google.compress" value="${basedir}/lib/compiler.jar" />
<apply executable="java" parallel="false" verbose="true" dest="${COMPRESSED_HOME}" taskname="js.compile">
<fileset dir="${basedir}">
<include name="*.js"/>
</fileset>
<arg line="-jar"/>
<arg path="${google.compress}" />
<arg line="--js" />
<srcfile/>
<arg line="--js_output_file"/>
<mapper type="glob" from="*.js" to="*-gcc-min.js" />
<targetfile />
</apply>
</target>

</project>


在build.xml文件的同级目录下有两个文件夹,一个名为lib, 内面放着YUI compressor和Google Closure Compiler的jar文件,另外一个是compressed文件夹,用于存放压缩过的js文件。

压缩时,把需要压缩的js文件放在build.xml文件的同级目录中,然后执行相应的ant命令就可以在compressed文件夹中得到压缩后的js文件了,下面分别是使用YUI Compressor和Google Closure Compiler压缩的命令:

ant yui-compress

ant google-compress
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: