经过几天搜索如何在Ant构建脚本中使用YUI Compressor,我终于让它工作了。关于创建Ant任务并在构建脚本中使用它,有许多旧的例子(<2010),但这对我来说是多余的。
许多示例也很老了,需要更多的Ant知识或配置Ant任务。下面的方法对我来说简单、快捷、有效。
以下内容被添加到我的一个<target>
标签中,以便在单个目录中压缩所有 javascript文件。这些文件保留其原始名称。对于CSS,只需将'js'切换为' CSS '并相应地更新路径。
这是用YUI Compressor 2.4.7完成的,我在Eclipse Juno中运行Ant构建脚本,没有更改类路径或其他修改设置。
<!-- Minimizing Javascript files -->
<echo message="Compressing Javascript files at location: ${build.root}/resources/js/*.js" />
<java jar="c:/dev/lib/yuicompressor-2.4.7/build/yuicompressor.jar" fork="true">
<arg value="${build.root}/resources/js/*.js" /> <!-- input path for JS files -->
<!--<arg value="-v" /> --><!-- Turn on verbose -->
<arg value="-o" />
<arg value="'.js$:.js'" />
<arg value="${build.root}/resources/js/*.js" /> <!-- output path for JS files -->
<classpath>
<pathelement location="c:/dev/lib/yuicompressor-2.4.7/build/yuicompressor.jar"/>
</classpath>
</java>
请随意改进这个答案。以上方法对我很有效,但我不是专家。
我使用以下解决方案来缩小文件,因为我得到了具有前一个答案的FileNotFoundException
。
要缩小CSS,将js
替换为css
。
<target name="compress" description="compress the JS files">
<copy todir="temp/js" overwrite="yes">
<fileset dir="original/js"/>
</copy>
<apply executable="java" parallel="false" dest="temp/js">
<fileset dir="temp/js" includes="**/*.js" />
<arg line="-jar"/>
<arg path="test_lib/yuicompressor-2.4.8.jar" />
<arg line="-v"/>
<srcfile/>
<arg line="-o"/>
<mapper type="glob" from="*.js" to="*-min.js"/>
<targetfile/>
</apply>
<move todir="original/js" overwrite="true">
<fileset dir="temp/js" />
<mapper type="glob" from="*-min.js" to="*.js"/>
</move>
</target>
我尝试了Victor的代码。实际上不需要临时目录。我使用了这个代码,它为我工作。
<apply executable="java" parallel="false" >
<fileset dir="${build.root}/resources/js" includes="**/*.js" />
<arg line="-jar"/>
<arg path="${basedirectory}/yuicompressor-2.4.8.jar" />
<srcfile/>
<arg value="-o" />
<arg value="'.js$:.js'" />
<!-- output path for JS files -->
<arg value="${build.root}/resources/js/*.js" />
<arg line="--nomunge" />
<arg line="--preserve-semi" />
</apply>
我将使用这个ant任务:http://code.google.com/p/yui-compressor-ant-task/或这个:https://github.com/parambirs/ant-yui-compressor,这似乎比应用更整洁。
你可以压缩所有可用的Js文件在一个特定的文件夹,而不复制到临时文件夹。
<property name="js.source" value="js/combine" />
<property name="js.target" value="js/compress" />
<fileset dir="${yuicompressor.lib}">
<include name="yui/yuicompressor-2.4.z8.jar"/>
</fileset>
<target name="minifyjs" description="compress the JS files">
<delete includeEmptyDirs="true">
<fileset dir="${js.target}" includes="**/*" defaultexcludes="no"/>
</delete>
<apply executable="java" parallel="false" verbose="true" failonerror="yes">
<fileset dir="${js.source}" includes="**/*.js" excludes="**/*-min.js, **/*.min.js"/>
<arg line="-jar"/>
<arg path="${yuicompressor.lib}" />
<srcfile/>
<arg line="-o"/>
<targetfile/>
<mapper type="glob" from="*.js" to="${js.target}/*.js"/>
<arg line="--charset"/>
<arg line="utf-8"/>
</apply>
</target>
上面的代码对我来说很好