作移动端项目的时候,页面优化的时候存在一个问题,引入的多个css和js会发出多个http请求,对页面的响应速度影响很大,全部想到用yahoo的一个js/css压缩工具YUI Compressor css
这里用的最新版本2.4.7.前端
在个人idea的工程目录的webapp目录下,我创建:java
一:创建了build目录,放置ant脚本build.xml文件 和 build.properties配置文件web
还创建了一个lib文件夹放置bulid的引入jar包服务器
因为在实际项目中,咱们须要对不一样的目录的资源文件压缩,所以通常经过循环完成多个目录的压缩。在本配置文件中,使用了额外的一个ant任务扩展包ant-contrib,自行下载。 该包在ant的基础上扩展了多个自定义任务。app
1;ant脚本build.xml文件代码以下:webapp
<?xml version="1.0" encoding="UTF-8"?> <project name="yui-compressor-demo" basedir="." default="yui-compress"> <description> yui-compressor-demo </description> <!--导入配置文件 --> <property file="build.properties"/> <tstamp> <format property="build.time" pattern="yyyy-MM-dd-HH-mm"/> </tstamp> <!--设置ant-contrib.jar用于逻辑判断 --> <taskdef resource="net/sf/antcontrib/antlib.xml"> <classpath> <pathelement location="${lib.build.antcontrib}"/> </classpath> </taskdef> <!--设置编译环境 --> <path id="build.classpath"> <fileset dir="${lib.build}"> <include name="*.jar"/> </fileset> </path> <!-- 建立build相关目录 --> <target name="init"> <delete dir="${deploy.dir}"/> <mkdir dir="${deploy.resource}"/> </target> <!--压缩合并css、js文件 --> <target name="yui-compress" depends="init"> <!-- 因为须要对css和js压缩,所以使用antcontrib ant扩展来作循环判断 --> <for list="${resources.include}" param="resoucesPath"> <!-- param表示在迭代的变量,使用时为@{resourcesPath} --> <sequential> <!--建立资源目录 --> <mkdir dir="${deploy.resource}/@{resoucesPath}/"/> <!--合并小文件为一个资源文件 --> <concat destfile="${deploy.resource}/@{resoucesPath}/merge-src.@{resoucesPath}" fixlastline="true" encoding="UTF-8"> <fileset dir="${resource.dir}/@{resoucesPath}"> <exclude name="merge.@{resoucesPath}"/> </fileset> </concat> <!--压缩资源文件 --> <apply executable="java" parallel="false" failonerror="true"> <fileset dir="${deploy.resource}/@{resoucesPath}"> <include name="*.@{resoucesPath}"/> </fileset> <arg line="-jar"/> <arg path="${lib.build.yuicompressor}"/> <arg line="--charset UTF-8"/> <srcfile/> <arg line="-o"/> <mapper type="glob" from="*.@{resoucesPath}" to="${deploy.resource}/@{resoucesPath}/merge-min.@{resoucesPath}"/> <targetfile/> </apply> </sequential> </for> </target> </project>
build.properties配置文件代码以下:ide
##工程根目录 project.dir=.. ##app目录 resource.dir=${project.dir}/ resources.include=css,js ##依赖包 lib.dir = ${project.dir}/lib lib.build=${lib.dir}/build lib.build.yuicompressor= ${lib.dir}/build/yuicompressor-2.4.7.jar lib.build.antcontrib= ${lib.dir}/build/ant-contrib-1.0b3.jar #发布目录 deploy.dir=${project.dir}/deploy deploy.resource=${deploy.dir}/resources
2:接着: svn
Ant Build面板中点击+号,能够引入一个build.xml配置文件,你能够引入多个,点击-号能够删除选中的配置文件。引入配置文件以后,选中须要运行的任务,能够是Project,也能够是Target,再点击上面的播放按钮就能够Run了工具
3:运行以后的结果:
这个过程就把我原来项目下webapp目录下的js和css文件夹下的多个js和多个css都压缩合并到
新建的一个deploy目录下了,这里看到,合并的merge-src.css和merge-src.js为源文件
压缩合并的merge-min.css和merge-src.js就是我要的。这样就能够把这两个文件部署上去用了,简洁多了。
这里我意识到Ant的强大:
后续有不少开发填坑的文章发布,若是对你有帮助,请支持和加关注一下