YUICompressor+ANT壓縮Java Web工程前端js/css檔案

來源:互聯網
上載者:User

最近team裡有個jsp工程想要做一些效能上的最佳化, 需要對工程裡的前端部分(主要是js和css)做一些壓縮(這是一個老舊重的工程,重構的成本非常大,也沒有人力,只能一步一步去最佳化)。想到與傳統ANT工具結合的比較好的yuicompressor。

yuicompressor下載

下載地址: http://maven.aliyun.com/nexus/service/local/repositories/central/content/com/yahoo/platform/yui/yuicompressor/2.2.5/yuicompressor-2.2.5.jar?spm=0.0.0.0.jwwQsz&file=yuicompressor-2.2.5.jar

這裡推薦下阿里雲的maven鏡像,下載速度很快。maven repository在國內經常被牆。

yuicompressor結合ant

yuicompressor做的東西和gulp類似,可以對js/css檔案做壓縮混淆,但在使用的過程中還是覺得不是很靈活方便,比如說它構建的目標檔案必須在構建前先建立好,這就要求我們在做構建之前先做一次copy操作。

我要實現的目的很簡單,在執行ant任務時,編譯java工程之前對工程裡的js/css檔案做混淆壓縮,最後打包成war包。所以我希望壓縮後的檔案能覆蓋舊的檔案,這樣一來我不需要去修改html/jsp檔案中對靜態資源的引用。

折騰一番後,對js或css檔案的壓縮的步驟大概總結為:

建立一個編譯目標目錄,將來源目錄下的檔案複製到目標目錄

將來源目錄中的檔案壓縮編譯後儲存到目標目錄

將目標目錄移動覆蓋來源目錄

以下是ant中壓縮js和css的任務:

<!--定義常量-->
<property name="yuicompressor.jar" location="${web.dir}/WEB-INF/lib/yuicompressor-2.2.5.jar"/>
<property name="js.src" location="${web.dir}/js/test_yui"/>
<property name="js.build" location="${web.dir}/js/test_yui_build"/>
<property name="css.src" location="${web.dir}/style"/>
<property name="css.build" location="${web.dir}/style_build"/>

<!--壓縮js-->
<target name="js.compress">
    <!-- START: 構建的目標檔案必須存在,所以現複製 -->
    <delete dir="${js.build}"/>
    <mkdir dir="${js.build}" />
    <copy todir="${js.build}" includeEmptyDirs="true" overwrite="true" preservelastmodified="true">
        <fileset dir="${js.src}" >
            <exclude name="**/*.*" />
        </fileset>
    </copy>
    <!-- END: 構建的目標檔案必須存在,所以現複製 -->

    <!-- START: js壓縮混淆 -->
    <apply executable="java" parallel="false" verbose="true" dest="${js.build}" >
        <fileset dir="${js.src}">
            <include name="**/*.js" />
            <exclude name="**/*.min.js" />
        </fileset>
        <arg line="-jar"/>
        <arg path="${yuicompressor.jar}" />
        <arg line="--type js --charset UTF-8 -o" />
        <mapper type="glob" from="*.js" to="*.js" />
        <targetfile />
    </apply>
    <!-- END: js壓縮混淆 -->

    <!-- START: 覆蓋來源目錄 -->
    <move todir="${js.src}">
        <fileset dir="${js.build}"/>
    </move>
    <!-- END: 覆蓋來源目錄 -->
</target>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.