Maleenc Maleenc - 1 year ago 130
Groovy Question

Gradle minify all javascript

I'm trying to minify all js files in my app. I was using gradle-js-plugin. I was able to minify a single file using that. But I want my all js files to be minified. Here is what i tried. It may seem very dumb in the end, but I'm new to writing something with gradle.

plugins {
id "com.eriwen.gradle.js" version "2.12.0"

task minifyAll << {

FileTree tree = fileTree('src/main/webapp/resourcesMinified') {
include '**/*.js'
exclude '**/*.css'
exclude '**/*.less'
exclude '**/*.sass'

tree.each { file ->
def path = file.path

minifyJs {
println path
source = path
dest = path
closure {
warningLevel = 'QUIET'

Problem is I can not invoke
task from inside
. I tried several things including
. Thanks in advanced.

Answer Source

Edit: now produces a minimized file for each JS file

I'm using Gradle 2.12 with several JS files in src/main/webapp/resources

Given this build.gradle file:

plugins {
    id "com.eriwen.gradle.js" version "2.12.0"

import com.eriwen.gradle.js.tasks.MinifyJsTask

def srcDir = "src/main/webapp/resources"
def dynamicTaskNames = []
def dynamicTaskIndex = 1

new File(srcDir).eachFile { def file ->
    def dynamicTaskName = "taskMinify${dynamicTaskIndex}"

    task "${dynamicTaskName}"(type: MinifyJsTask) {
        source = file.absolutePath
        dest = "${buildDir}/min.${}"
        closure { warningLevel = 'QUIET' }

    dynamicTaskNames << dynamicTaskName

task myMinify(dependsOn: dynamicTaskNames) << {
    println ("done.")

The following works for me:

$ gradle myMinify

The myMinify task has dependencies on several, dynamic tasks which perform the minifyJs task for each file. e.g. StringUtils.js will generate build/min.StringUtils.js.

I use the ICE rule when thinking about Gradle: Initialization phase, Configuration phase, Execution phase. In this case, the dynamic tasks are defined during the Configuration phase (i.e. the code that floats freely outside of a task definition). During the Execution phase, myMinify calls its dependencies, where the work is performed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download