Ant+yuicompressor merge compression js and CSS code instances

Source: Internet
Author: User
Tags echo message glob goto http request pack


In the actual project, the recommendation is an HTML corresponding to a JS file and a CSS file. Doing so reduces the HTTP request, and it is well known that an HTTP request has a much longer delay than downloading a larger file.

So from the programmer's point of view: I want to separate files, modules to write. Otherwise the code is too confusing. (Multiple files)

Customers (users of the site) look: I want a good user experience, the faster the better. (fewer files, more HTTP requests will be a lot of files)

This creates a conflict, but there is a market for demand, and our clever front-end siege Lion has its own way of solving it. --Link file with compression Dafa, which is titled "Use Ant and Yuicompressor links to merge and compress your JS and CSS code."

Ant, the Chinese translation is "ant". Yes, well, this is an Apache project, a Java build tool that merges or replicates code files from some projects. The specific stuff can be Google or Baidu

Official website: http://ant.apache.org/

Yuicompressor, Yahoo Company's a code compression tool, seemingly compression ratio is very high. A bunch of online compression sites on the Internet are also doing this. is also based on Java.

The first step: with the Java environment

Skip this step, it's so simple, right? Ant and Yuicompressor are all based on Java, do not know their own Google or Baidu, here is the environment variable where the configuration. Not in Eclipse. Well, I know you thought of-_-!!。 It is estimated that many of them have been matched without much to say.

Step Two: Create the project

Create a new project under Eclipse, Dynamic Web project. Open the Project Explorer window (Window->show View)







As shown, I set up a anttest project and then set up three folders under WebContent,

Build this folder is used to put the link merging and compression tools
Build_output This folder is used to put the front-end code and page of the project online
Web This is used to put some of the code of the parts of the unlinked compression, the usual editing code in the folder under the Edit and modify

Step three: Create specific files












This picture is a Web folder under the specific file module, in fact, some of the modules jquery can be disconnected to load.

Step Fourth: Place the tool files inside the build folder




This is the Ant and Yuicompressor folder. Just unzip it and put it inside.

Ant also needs to be equipped with the environment, such as the following

Ant_home d:/apache-ant-1.9.0
Path d:/Apache-ant-1.9.0/bin
Classpath D:/apache-ant-1.9.0/lib

Step Fifth: Set up profile Build.xml

We are here with


<? xml version = "1.0" encoding = "UTF-8"?>
 
<project default = "compress" basedir = "D: \ eclipseWorkSpace \ AntTest \ WebContent \ web" name = "core">
    <!-The web path of the project, which is the path of the web folder where we modified the code->
    <property name = "path" value = "D: \ eclipseWorkSpace \ AntTest \ WebContent \ web" />
    <!-The output path of the deployment is also the path of the project's link merged compressed output folder->
    <property name = "targetDir" value = "D: \ eclipseWorkSpace \ AntTest \ WebContent \ build_output \ asset" />
    <!-Source file path (src)->
    <property name = "code.src" value = "src" />
    <property name = "baseService" value = "baseService" />
    <!-!!! YUI Compressor path !!!->
    <property name = "yuicompressor" value = "D: \ eclipseWorkSpace \ AntTest \ WebContent \ build \ yuicompressor-2.4.6 \ yuicompressor-2.4.6 \ build \ yuicompressor-2.4.6.jar" />
         
    <!-==================================
         target: concat stitching (merging) files
    ===================================->
          
    <target name = "concat" depends = "" description = "concat code">
        <echo message = "Concat Code Files Begin !!!" />
        <!-Note that the order of stitching here is the priority to merge files, which means the meaning of dependencies-> <!-JS->
        <concat destfile = "$ {targetDir} /js/source/all.js" encoding = "utf-8" fixlastline = "on">
            <fileset dir = "$ {code.src} / js" includes = "jquery-1.5.1.js" />
            <fileset dir = "$ {code.src} / js" includes = "jquery.ui.core.js" />
            <fileset dir = "$ {code.src} / js" includes = "jquery.ui.widget.js" />
            <fileset dir = "$ {code.src} / js" includes = "jquery.ui.draggable.js" />
            <fileset dir = "$ {code.src} / js" includes = "jquery.ui.droppable.js" />
            <fileset dir = "$ {code.src} / js" includes = "jquery.ui.button.js" />
            <fileset dir = "$ {code.src} / js" includes = "jquery.ui.dialog.js" />
            <fileset dir = "$ {code.src} / js" includes = "jquery.ui.accordion.js" />
            <fileset dir = "$ {code.src} / js" includes = "jquery.ui.autocomplete.js" />
        </ concat>
        <!-CSS->
        <concat destfile = "$ {targetDir} /css/source/all.css" encoding = "utf-8">
            <fileset dir = "$ {code.src} / css" includes = "jquery.ui.core.css" />
            <fileset dir = "$ {code.src} / css" includes = "jquery.ui.button.css" />
            <fileset dir = "$ {code.src} / css" includes = "jquery.ui.dialog.css" />
            <fileset dir = "$ {code.src} / css" includes = "jquery.ui.accordion.css" />
            <fileset dir = "$ {code.src} / css" includes = "jquery.ui.autocomplete.css" />
        </ concat>
 
        <echo message = "Concat Code Files Finished !!!" />
    </ target>
 
    <!-==================================
          target: copy
         ===================================->
 
    <target name = "copy_asset" depends = "concat" description = "copy the asset file">
        <echo message = "Copy Asset Begin" />
        <!-main.html->
        <copy todir = "$ {targetDir} /../" overwrite = "true">
            <fileset dir = "$ {path} /" includes = "*. html" />
        </ copy>
        <!-img * .png->
        <copy todir = "$ {targetDir} / img" overwrite = "true">
            <fileset dir = "$ {path} / asset / img" includes = "*. png" />
        </ copy>
 
        <echo message = "Copy Asset Finished" />
    </ target>
 
 
    <!-==================================
          target: compress js && css
         ===================================->
 
    <target name = "compress" depends = "copy_asset" description = "compress code">
        <echo message = "Compress Code Begin" />
 
        <apply executable = "java" parallel = "false" failonerror = "true" dest = "$ {targetDir} / js">
            <fileset dir = "$ {targetDir} / js / source" includes = "*. js" />
            <arg line = "-jar" />
            <arg path = "$ {yuicompressor}" />
            <arg line = "-charset utf-8" />
            <arg line = "-o" />
            <targetfile />
            <mapper type = "glob" from = "*. js" to = "*. js" />
        </ apply>
         
        <apply executable = "java" parallel = "false" failonerror = "true" dest = "$ {targetDir} / css">
            <fileset dir = "$ {targetDir} / css / source" includes = "*. css" />
            <arg line = "-jar" />
            <arg path = "$ {yuicompressor}" />
            <arg line = "-charset utf-8" />
            <arg line = "-o" />
            <targetfile />
            <mapper type = "glob" from = "*. css" to = "*. css" />
        </ apply>
 
        <echo message = "Compress Code Finished" />
 
        <echo message = "Clean Begin" />
 
        <!-<delete verbose = "false" failonerror = "true">
            <fileset dir = "$ {path}" includes = "$ {targetDir} / *-o.js" />
        </ delete>->
 
        <echo message = "Clean Finished" />
 
    </ target>
</ project> 



Run with Ant's instructions at the command prompt (CMD) (Don't tell me you don't ...) , learn Java should understand, Javac well, a truth:




In fact, the flow is almost the same, but, lazy people always have a lazy way, above also to play a command prompt, and then, they made a simple batch file.

Step Sixth: Create the BUILD.bat batch file to automatically execute the ANT directive

right mouse button to create a TXT file, and then enter






@echo off
Ant
Pause




Here BUILD.bat and Build.xml are placed under the same path. So you can call the instructions directly, if you want to put it somewhere else you want to change the path.

Then save, the suffix txt changed to bat on it.

Later, after modifying the code, press BUILD.bat keyboard F3 (Eclipse Open File shortcut key) can be linked to merge compression of your JS and CSS code.



Of course, if you do not want to compress the words only want to merge, the Build.xml compressed that block deleted on it.

There are still some small problems with this, the background developers if you want to set path mapping those words are actually going to the Build_output folder to do, because this folder is the page's real address (code has been merged compression).

Just remember to tell them.





use Yui compressor compression js and CSS, batch processing, right button, registry, packaging

For AJAX applications that use JavaScript and CSS in large quantities, if JavaScript and CSS are large in size, they can be transmitted to the client for a long time, with poor Web performance. and compressed JavaScript and CSS is a natural thing (which Yui compressor compression rate of about 50%)

YUI compressor-the Yahoo! JavaScript and CSS compressor

YUI Compressor Compressed JavaScript content includes:

To remove a comment
Removing extra spaces
Fine tuning
Identifier substitution (Identifier replacement)


Download Download Address: http://yuilibrary.com/downloads/#yuicompressor
The YUI compressor requires Java version >= 1.4. (The machine needs more than 1.4 Java environments) so download the JDK first and configure the environment.

First, Java environment configuration
The steps for JDK environment variable configuration are as follows:
1. My Computer--> Properties--> advanced--> environment variables.
2. Configure User variables:
A. New Java_home
C:\Program files\java\j2sdk1.5.0 (Installation path for JDK)
B. New PATH
%java_home%\bin;%java_home%\jre\bin
C. New CLASSPATH
.; %java_home%\lib;%java_home%\lib\tools.jar
3. Test environment variable Configuration success:
Start--> Run--〉cmd
Keyboard typing: JAVAC
The corresponding command, not the error message, indicates that the configuration was successful!

second, the use of Yui compressor compression js and CSS

Common examples (performed in cmd)

Java-jar D:\yuicompressor-2.4.6\build\yuicompressor-2.4.6.jar--type js--charset UTF-8 D:\my.js-o D:\my-min.js

Java-jar D:\yuicompressor-2.4.6\build\yuicompressor-2.4.6.jar--type css--charset UTF-8 D:\my.css-o

? type specifies the type of file to package, optionally JS and CSS
? charset specified character set
-o Specifies the file name of the output, and if this parameter is not specified, the compressed content is output to the command line
The final my.js and My.css are the debug version of the source file to be packaged

If you do not have a given charset parameter, the character set defaults to the system, where UTF-8 is specified, and your actual needs are modified. Specific syntax and other parameter references: http://www.julienlecomte.net/yuicompressor/

Use Yui compressor and DOS batch script compression JavaScript and CSS, plus IIS gzip, add up to get about 85% of the compression rate. (of which Yui compressor compression rate of about 50%) can also modify parameters to obtain more compression rate.


third, the production of batch processing tools

Three files:
Batch file: Yuicompressor.bat
Registry file: Yuicompressor.reg
Compress jar Package: Yuicompressor-2.4.6.jar

File directory: D:\server\f2etools\yuicompressor

How to use Yuicompressor.bat batch processing:
Right click on the entire folder "Yui-compressor js/css" batch compression operation to generate-MIN.CSS or-min.js, the source file unchanged, the project at ordinary times to refer to the source file, the line before the reference compressed file test normal after the line.

Yuicompressor.bat Batch File code:

CD '%1 '
for/f%%a in (' dir/b *-min.js ') do Call:processdel:%%a
for/f%%a in (' dir/b *-min.css ') do Call:processdel:%%a
for/f%%a in (' dir/b *.js ') do call:processcompress:%%a
for/f%%a in (' dir/b *.css ') do call:processcompress:%%a


:P Rocessdel

IF not [%1]==[] Call:deleteminfiles:%1

Goto:eof

:P rocesscompress

IF not [%1]==[] Call:compressfiles:%1

Goto:eof

:D Eleteminfiles

IF EXIST "%cd%\%1" del "%cd%\%1"

Goto:eof

: Compressfiles

Java-jar D:\server\f2etools\yuicompressor\yuicompressor-2.4.6.jar%1-o%~n1-min%~x1

Goto:eof



Yuicompressor.reg registry function: When the folder is selected, the right key will be one more option "Yui-compressor js/css"
Yuicompressor.reg Registry File Code:

Windows Registry Editor Version 5.00

[Hkey_classes_root\directory\shell\compress js/css Files]
@= "Yui-compressor js/css"

[Hkey_classes_root\directory\shell\compress js/css Files\command]
@= "D:\\server\\f2etools\\yuicompressor\\yuicompressor.bat%1"



Download Address: Http://heiniu.me/tools/yuicompressor.rar

Note: Please modify the directory path in the two files
Batch files: Yuicompressor.bat and registry files: Yuicompressor.reg

Iv. packing and compressing pack-all-min.js

The documents are as follows:
Batch file: Pack-js.bat
directory files that need to be packaged: Pack-list.txt

Pack-js.bat Code:
for/f%%i in (packList.txt) do type%%i >> pack-all.js

Java-jar D:\server\f2etools\yuicompressor\yuicompressor-2.4.6.jar--type js--charset utf-8 pack-all.js-o Pack-all-min.js

Pack-list.txt
Jquery.ui.datepicker.js
Jquery.ui.dialog.js
Jquery.ui.draggable.js
Jquery.ui.mouse.js

How to use:
In the current JS folder into the two files, usually developed with multiple source files, run Pack-js.bat after viewing the page effect, the line before packaging into a compressed file, the test is correct and then online.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.