Maven plugin to concat and minify javascript

Mady picture Mady · May 25, 2013 · Viewed 25.3k times · Source

I have 100s of javascript files inside the hierarchy of folders and I want two sets of output. one is to have a concatenated version for debugging purposes and the other one is to have a concat + minfy version. I am currently using the below plugin but in this I need to provide each and every file that I need to minify. I am looking for a plugin which needs only parent folder and satisfy the above conditions.

<groupId>com.samaxes.maven</groupId>
<artifactId>minify-maven-plugin</artifactId>
<version>1.7</version>

Answer

Mady picture Mady · May 26, 2013

YUI compression maven plugin worked for me. I will show what all I did to make it work.

  • To concatenate all the js files I used aggregation.

Details of the elements used.

  • preProcessAggregates - To process aggregation before minification.
  • aggregations - To aggregate the multiple resources in folder hierarchy to a single file.
  • aggregation - There can be multiple aggregation elements inside parent aggregations.
  • insertNewLine - Insert newline after each file eof, while concatenation/aggregation of files.
  • inputDir - Parent directory inside which files would be searched for concatenation/aggregation.
  • sourceDirectory - Directory under which files would be searched for minification.
  • outputDirectory - Directory under which minified output would be placed.
  • nosuffix - If set to true, then plugin will not add '-min' to the minified file.

There are 2 types of <exclude> property:-

  • First is part of aggregation, which basically excludes files from aggregation.
  • Second is part of the plugin to exclude files from minification.

Plugin code:-

<plugin>
  <groupId>net.alchim31.maven</groupId>
  <artifactId>yuicompressor-maven-plugin</artifactId>
  <version>1.3.2</version>
  <configuration>
    <preProcessAggregates>true</preProcessAggregates>
    <aggregations>
      <aggregation>
        <insertNewLine>true</insertNewLine>
        <output>${basedir}/target/single.js</output>
        <inputDir>${basedir}/src/main/resources/js</inputDir>
        <includes>
          <include>**/*.js</include>
        </includes>
        <excludes>
          <exclude>**/*abc.js</exclude>
          <exclude>**/compressed.css</exclude>
        </excludes>
      </aggregation>
    </aggregations>
    <excludes>
      <exclude>**/*-min.js</exclude>
      <exclude>**/*.min.js</exclude>
      <exclude>**/*-min.css</exclude>
      <exclude>**/*.min.css</exclude>
    </excludes>
    <jswarn>false</jswarn>
    <nosuffix>false</nosuffix>
    <sourceDirectory>${basedir}/target</sourceDirectory>
    <outputDirectory>${basedir}/target</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <id>compress_js_css</id>
      <phase>process-resources</phase>
      <goals>
        <goal>compress</goal>
      </goals>
    </execution>
  </executions>
</plugin>