使用yuicompressor-maven-plugin压缩js及css文件

本文介绍通过使用yuicompressor-maven-plugin插件实现js及css代码的自动压缩,方便集成到持续集成环境中,如jenkins。

一、配置yuicompressor-maven-plugin

在pom文件中增加该插件的定义,示例如下:

    <plugin>
        <groupId>net.alchim31.maven</groupId>
        <artifactId>yuicompressor-maven-plugin</artifactId>
        <version>1.3.0</version>
        <executions>
            <execution>
                <goals>
                    <goal>compress</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <encoding>UTF-8</encoding>
        <!-- 忽略 js 错误警告 -->
            <jswarn>false</jswarn>
            <nosuffix>true</nosuffix>
            <linebreakpos>-1</linebreakpos>
            <includes>
                <include>js/**/*.js</include>
                <include>css/**/*.css</include>
            </includes>
            <excludes>
                <exclude>**/**min.js</exclude>
                <exclude>js/ba/**/*.js</exclude>
            </excludes>
        </configuration>

</plugin>

1、execution表示执行的操作,可以指定操作在maven的哪个生命周期运行,不同的生命周期对打包操作会有影响,如配置在compile阶段运行压缩:

    <executions>
        <execution>
        <phase>compile</phase>
            <goals>
                <goal>compress</goal>
            </goals>
        </execution>
    </executions>

2、经验证发现该插件运行时所在的位置是项目编译打包的输出路径,比如项目名称为abc,当前文件夹应为project_root/target/abc。maven在打包的时候会把所有编译的文件、webapp下的文件复制到该目录中为打包做准备。

3、include节点用于配置需要压缩的文件路径,可以使用通配符,*表示一个文件或路径名,**表示多个文件或路径名,exclude节点用于配置排除压缩的文件路径,exclude只会排除include中设置的路径下的文件或路径。

二、配置maven-war-plugin

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
            <warName>${artifactId}</warName>
            <warSourceExcludes>js/**/*.js,css/**/*.css</warSourceExcludes>
        </configuration>
    </plugin>

在配置过程中发现无论将phase设置为哪个阶段,最终打包的文件总是原始文件,并未被压缩,后来测试发现maven-war-plugin会自动把webapp目录下的文件复制到输出路径,因此可以通过warSourceExcludes配置排除复制,的文件或路径,如上例中指定排除js目录下的所有js文件,css目录下的所有css文件。

三、常见错误

压缩js文件时,如果代码中包含debugger,yuicompressor会认为其为保留关键字,注释或删除可以使打包正常进行,也可以使用eval('debugger')替换debugger。

[ERROR] ...\src\main\webapp\js\Scroll.js:line 371:column 11:identifier is a reserved word debugger;

[ERROR] ...\src\main\webapp\js\Scroll.js:line 1:column 0:Compilation produced 1 syntax errors.

四、相关资料

插件主站地址:http://alchim.sourceforge.net/yuicompressor-maven-plugin/

插件配置参数:http://alchim.sourceforge.net/yuicompressor-maven-plugin/compress-mojo.html#resources

配置示例:http://www.myexception.cn/operating-system/427170.html

posted @ 2013-07-08 10:14  没头脑的土豆  阅读(9362)  评论(0编辑  收藏  举报