下面讲讲如何用Google Closure Compiler和ant合并和压缩js文件:
1、Google Closure Compiler依赖于java,如果你的机子还没有安装java运行时,请下载及安装。
2、下载Google Closure Compiler:http://code.google.com/p/closure-compiler/。
3、下载ant:http://ant.apache.org/bindownload.cgi。
4、建立build.xml文件,这个是ant运行的配置文件。格式如下:
<?xml version="1.0"?>
<project name="Javascript compress project" basedir="." default="compile">
<taskdef name="jscomp" classname="com.google.javascript.jscomp.ant.CompileTask" classpath="<path>/compiler-latest/compiler.jar"/>
<target name="compile" depends="clear">
<jscomp compilationLevel="simple" warning="quiet" debug="false" output="../js/Main.min.js">
<sources dir="${basedir}">
<file name="../js/aaa.js"/>
<file name="../js/bbb.js"/>
</sources>
</jscomp>
</target>
<target name="clear">
<delete file="../js/Main.min.js"/>
</target>
</project>
其中要修改classpath为相应的路径,以及添加自己的js文件,还有输出的文件,注意:js文件要根据调用顺序来罗列。上面文件的意思是先清理生成的内容,再进行压缩。
5、运行:在命令行下,
cd <project-path>
<ant-path>/bin/ant
设置当前工作目录到build.xml所在文件夹,然后调用ant命令(为了方便,你可以把ant加入到system path),这个时间ant默认会自动调用build.xml
来运行相关的任务。生成的过程
如下图:
到此,整个过程完成。