Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle minify all javascript

Tags:

gradle

groovy

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 minifyJs task from inside minifyAll. I tried several things including execute.

like image 970
Maleen Abewardana Avatar asked Feb 26 '26 05:02

Maleen Abewardana


1 Answers

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.${file.name}"
        closure { warningLevel = 'QUIET' }
    }

    dynamicTaskNames << dynamicTaskName
    dynamicTaskIndex++    
}

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.

like image 100
Michael Easter Avatar answered Feb 28 '26 04:02

Michael Easter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!