Gradle Tasks for JavaScript and CSS Minification and Combination using ThreadPoolExecutor for Parallel Execution

This is my first post for this blog. And, I am going to start with a posting a task I created for Gradle, for minification and combination of JS and CSS, that too using a ThreadPoolExecutor for faster minification and combination
. Following is an explanation of each section, and finally there will the complete code that you would have to add to your Gradle Build Script. So, lets go!

First, we include the important stuff to start :-

Now, we will write a snippet, which will represent all JS files in a code base :-

This will find all JavaScript files, recursively in all underlying folders. Let’s write something similar for CSS, shall we ? :-

Easy ? Good!

The idea for minification and combination, is that, we need to create a task for each file for minification, and each section for combination. That is, we create tasks dynamically, as follows :-

All tasks here will be created with a name jsMinifyTask_{index}. Again, one task per file for minification.

Something similar for CSS :-

This code will create tasks for minification of CSS files, one at a time.

For combination, I wrote a small JSON structure to make it easy for maintenance. The JSON is :-

This is pretty self explanatory, I guess ? Add up more to make more combined files.

The code which uses this to create tasks for combining files is :-

So now, we are done with creating tasks, and it is time to make them run! I created a wrapper task for this. This will minify all files parallely, and then combine them, parallely. Makes it faster 😉

Runtime.runtime.availableProcessors() will find all available processors and use them.

All that is required now is, writing a simple ‘dependsOn minify’ in the tasks you already have in your build scripts. Voila!

For reference, the complete code is :-

Let me know in comments in case you have problems 🙂