Edi Weissmann

I code for fun /* and profit */

Minify .js and .css During Maven Build

Pagespeed logo

I want to minify static js and css files for a website. I want to combine all files into one js file and one css file. And I want to do that during the Maven build.

One solution is a combination of minify-maven-plugin and maven-replacer-plugin

Since it’s Maven based, there’s tons of xml configuration involved. Thankfully, this guy from Stockholm created a sample project on github showing how all plugins are configured together. It’s pretty easy to follow his setup and that’s what I did.

I had some issues about the order in which the .js files were included in the minified bundle: my app’s dependencies should have appeared before my app’s sources. They didn’t.

I learned that I could solve this by creating two .js bundles: one for my dependencies and one for my app.

1
2
3
4
5
6
7
8
9
10
<-- deps bundle: include all .js libs except my app -->
<jsSourceIncludes>
  <jsSourceInclude>**</jsSourceInclude>
</jsSourceIncludes>
<jsSourceExcludes>
  <jsSourceExclude>**/application.js</jsSourceExclude>
</jsSourceExcludes>
<jsFinalFile>myapp-dep-${maven.build.timestamp}.bundle.js</jsFinalFile>

<-- add another bundle that just contains my app's js files: application.js -->

Now each time mvn package is run, the css and js files are minified.

If I need to debug the .js in original formatting, I launch the website from the IDE, and the mvn goal to minify is not invoked.