Add generated files with gradle before WAR creation

During development we are using javascript and CSS files that are not minified. But they have to be minified (with yuicompressor) when the production war is built. So, I want to replace the original javascript and CSS files with the minified ones. The project structure looks as follows (nothing special):

+ webapp
|-- js
|-- css
...

What I want to do is: before the WAR is created by Gradle, I want to minify the above mentioned files with yuicompressor and want them to be packed in the WAR.

What I did so far is to run a task before the WAR is created, which minifies the files:

war {
   it.dependsOn minifyJavaScript
}

The task minifyJavaScript takes all files in the webapp/js folder, minifies them and store them in the ${buildDir}/js directory. The only thing I couldn’t get to work is that these files are packed into the WAR. I tried to adjust the sourceSets, but I got an error from Gradle:

apply plugin: 'java'
  ...
sourceSets {
    main {
        webapp {
            srcDir "${buildDir}/js"
        }
    }
}

Error: unsupported Gradle DSL method found: ‘sourceSets()’

I also tried to include the files with with:

war {
   it.dependsOn minifyJavaScript
   include ${buildDir}/js
}

The problem with this solution is that the WAR contains only the minified files.

So, is there a way to tell Gradle to add the ${buildDir}/js path during WAR creation? Or is there a better / simpler way to include the minified files?

Try doing

war {
  dependsOn minifyJavaScript
  from( "${buildDir}/js" )
}

instead.

Thanks. I forgot to mention, that I tried this too. The problem here is, that all files are now in the root directory of the WAR file, they are not copied into the js folder.

I also tried to have another directory ${buildDir}/minified/js and do

from ${buildDir}/minified

Now, all files in the js directory are duplicated.

Stupid me! I missed ‘with’. Try this instead:

war {
  with {
    from( "${buildDir}/js" )
    into 'js'
  }
}

If I use into ‘js’, js is the new root directory in the created WAR. This means, that if you unpack the WAR, you will have a js directory and in this js directory, you will have all the other directories and files.

If I do not use into ‘js’ it is still the same.

But, thanks again.

But this one is working:

exclude "js"
        from( "${buildDir}/minified/js", {
            into 'js'
        })

I exclude all not minified files under js and than copy all the minified files into a folder called js.

That was hard…

1 Like

Excellent!