1. 程式人生 > >jenkins ant build的時候壓縮JS/CSS程式碼

jenkins ant build的時候壓縮JS/CSS程式碼

1、下載YUIAnt.jar 和 yuicompressor-2.4.2.jar,放到你專案的libs裡。

2、build.xml增加如下配置,以我的phonegap程式為例:

 <property name="www.dir" value="./assets/www" />		
<path id="yuiClasspath">
			<fileset dir="./libs">
				<include name="yuicompressor-2.4.2.jar"/>
				<include name="YUIAnt-zh_CN.jar"/>
			</fileset>
		</path>
	
	<target name="compres-js-css">
			<taskdef name="yuicompress" classname="com.yahoo.platform.yui.compressor.YUICompressTask">
				<classpath>
					<path refid="yuiClasspath"/>
				</classpath>
			</taskdef>
			<yuicompress linebreak="500" warn="false" charset="utf-8" encoding="utf-8" munge="yes" 
				preserveallsemicolons="true" outputfolder="${www.dir}">
				<fileset dir="${www.dir}">
					<include name="scripts/url.js" />
					<include name="scripts/mission.js" />
					<include name="scripts/history.js" />
					<include name="scripts/examination.js" />
				</fileset>
			</yuicompress>
		</target>

3、上面增加了一個target:compress-js-css,要在 target name="-set-release-mode" 的depends里加入這個target

4、我一開始用的Ant是1.8.3版本,會報錯:

java.lang.IllegalAccessError: tried to access class org.mozilla.javascript.DefaultErrorReporter from class org.mozilla.javascript.CompilerEnvirons
	at org.mozilla.javascript.CompilerEnvirons.<init>(CompilerEnvirons.java:48)
	at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:312)
	at com.yahoo.platform.yui.compressor.JavaScriptCompressor.<init>(JavaScriptCompressor.java:536)
	at com.yahoo.platform.yui.compressor.YUICompressTask.doCompression(YUICompressTask.java:202)
	at com.yahoo.platform.yui.compressor.YUICompressTask.execute(YUICompressTask.java:101)
	at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
	at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
	at org.apache.tools.ant.Task.perform(Task.java:348)
	at org.apache.tools.ant.Target.execute(Target.java:392)
	at org.apache.tools.ant.Target.performTasks(Target.java:413)
	at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
	at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
	at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
	at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
	at org.apache.tools.ant.Main.runBuild(Main.java:811)
	at org.apache.tools.ant.Main.startAnt(Main.java:217)
	at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
	at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)

解決:改成用1.8.1的Ant版本即可。

如果你的環境是jenkins,可以讓管理員配置多一個Ant版本既可以,然後在專案的配置裡,選擇該版本,如下圖: