Specify File Order for Combining JavaScript Files through gradle-js-plugin

Posted by & filed under , .

gradle_logoIf you use Gradle builds to combine and minify JavaScript source files via the gradle-js-plugin (thanks, Eric!), you might have run into the same problem as I did: ordering of the files!

The Github docco doesn’t mention (yet!) anything around it and you are left to guess that doing something like this will sort out your ordering:

combineJs {
  encoding = "UTF-8"
  source = ["fileB.js", "fileA.js"]
  dest = file("${buildDir}/all.js")

And you will get in the combined (output) javascript fileB.js source before fileA.js.

Well, you’re wrong! You go down that route it seems the source files will always be alphabetically sorted.

The workaround this issue that I found consists of 2 changes in one go:

  1. Define your own custom task
  2. AND also specify a files collection

Like this:

task combineJsSource(type: com.eriwen.gradle.js.tasks.CombineJsTask) {
  source = files("fileB.js", "fileA.js")
  dest = file("${buildDir}/all.js")

This works beautifully and you can still use its output in a minifyJs task:

minifyJs {
  source = combineJsSource

You can see in fact the full discussion on Github which concluded with this solution here: https://github.com/eriwen/gradle-js-plugin/issues/4

You’re welcome! 🙂