[:ru]Сборка, минимизация и деплой JS средствами Gradle[:en]JS build and deploy with Gradle[:]
[:ru]Рано или поздно любой JS проект вырастает из детских штанцов, обьем и частота коммитов растут, а решение становится сложным комплексом и состоит из десятков JS файлов.
В результате приходится регулярно производить множество операций по склеиванию, минимизации и загрузке на сервер обновленных модулей. День за днем, чекин за чекином ситуация становится все сложнее и грозит выйти из под контроля, выводя из себя, загружая вас рутинной работой. А впереди возможно светит Continous Integration и автоматическое тестирование…
Избавить вас от рутинных хлопот поможет система сборки. Gradle является одной из самых популярных систем на сегодня и постепенно завоевывает все больше сторонников. Приемуществом Gradle является описание build задач в виде кода, а так же возможность запускать Ant и Maven таски.
[:en]There is one extremely surprising thing — JS projects growth!
Wow! That`s cool. But…
Combining, minimization and deploying of this dozens of files would become larger and larger problem.
Gradle is popular and modern build system that can solve such problems for you with help of JavaScript Gradle plugins.
[:][:ru]
Специально для комбинации и минимизации JS файлов существует два Gradle плагина — https://launchpad.net/gradle-jslib и https://github.com/eriwen/gradle-js-plugin.
По состоянию на декабрь 2011 года первый обладал хорошими возможностями по комбинации файлов в модули, однако не работал с последней версией Gradle. Рассказ в статье пойдет о втором плагине — он прост в освоении, надежен и снабжен неплохой документацией.
Начнем с установки gradle — она достаточно проста. Качаем свежий пакет с http://gradle.org/downloads . Распаковываем на диске и добавляем подпапку bin в path. Как добавить переменную в path — можете почитать тут http://stackoverflow.com/questions/7703041/editing-path-variable-on-mac.
Проверить работоспособность Gradle мы можем выполнив команду gradle в терминале.
Следующий шаг — написание непосредственно Gradle скрипта.
buildscript {
repositories {
mavenCentral()
}
dependencies {
//Устанавливаем плагин из Maven репозитория
classpath 'com.eriwen:gradle-js-plugin:0.3'
}
}
//Применяем плагин
apply plugin: 'js'
//Таск плагина на склеивание, задаем inputs и outputs
combineJs {
file1 = fileTree(dir: "${projectDir}/src/Core", includes: ['Framework/core.js'])
file2 = fileTree(dir: "${projectDir}/src/Core", includes: ['Framework/strings.js'])
file3 = fileTree(dir: "${projectDir}/src/Core", includes: ['Framework/dom.js'])
inputs.files file1 + file2 + file3
outputs.file file("${projectDir}/min/corecombined.js")
}
//Таск плагина на минификацию, задаем inputs и outputs
minifyJs {
inputs.files fileTree(dir: "${projectDir}/min", include: "corecombined.js")
outputs.file file("${projectDir}/min/core.min.js")
}
А для деплоя используем Ant таск, который опишем в отдельном файле — deploycore.xml, а затем запустим из gradle — скрипта :
<project>
<target name="deployFiles"> //По этому имени таск будет доступен из Gradle
<echo message="ANT_HOME is set to = ${basedir}" />
<taskdef name="ftp" classname="org.apache.tools.ant.taskdefs.optional.net.FTP">
<classpath>
<pathelement location="${basedir}/antlibs/ant-commons-net.jar" />
<pathelement location="${basedir}/antlibs/commons-net-3.0.1.jar" />
<pathelement location="${basedir}/antlibs/jakarta-oro-2.0.8.jar" />
</classpath>
</taskdef>
<ftp server="staging.oggifinogi.com" userid="administrator" password="xxx" port="21" remotedir="/components" passive="yes" binary="no">
<fileset dir="min/">
<include name="*.min.js" />
</fileset>
</ftp>
</target>
</project>
Добавим последнюю строку в core.gradle, которая загрузит все файлы с маской *.min.js на FTP :
ant.importBuild 'deploy.xml'
И наконец — вызываем gradle из консоли:
gradle -b=core.gradle combineJs minifyJs deployFiles
Наши файлы скомбинированы, уменьшены и загружены на сервер.
Теперь вы можете уделить больше времени написанию кода.[:en]
There are two Gradle plugins for building JavaScript — https://launchpad.net/gradle-jslib and https://github.com/eriwen/gradle-js-plugin.
At December 2011 first have nice feature to split project into modules, but it didn`t work with last Gradle version (hope someday it will). This article would be about second one — it`s simple, robust and well documented.
Let`s start from installing Gradle — it`s simple enough. Let`s download fresh version from http://gradle.org/downloads , unpack it and add «bin» subdir to path. Here is good description of how to work with PATH variables — http://stackoverflow.com/questions/7703041/editing-path-variable-on-mac.
After PATH is correct and applied we`ll check Gradle installation with executing Gradle command in console.
Next step is to write buildscript in Groovie. In fact you have not to be Groovie developer to accomplish this:
buildscript {
repositories {
mavenCentral()
}
dependencies {
//Installing plugin from Maven repository
classpath 'com.eriwen:gradle-js-plugin:0.3'
}
}
//Applying plugin
apply plugin: 'js'
//Concatination task, defining inputs and outputs
combineJs {
file1 = fileTree(dir: "${projectDir}/src/Core", includes: ['Framework/core.js'])
file2 = fileTree(dir: "${projectDir}/src/Core", includes: ['Framework/strings.js'])
file3 = fileTree(dir: "${projectDir}/src/Core", includes: ['Framework/dom.js'])
inputs.files file1 + file2 + file3
outputs.file file("${projectDir}/min/corecombined.js")
}
//Minification, the same with inputs and outputs
minifyJs {
inputs.files fileTree(dir: "${projectDir}/min", include: "corecombined.js")
outputs.file file("${projectDir}/min/core.min.js")
}
For deploying minified JavaScript we`ll use Ant task, have to create separate file for it — deploycore.xml, and then launch from main script :
<project>
<target name="deployFiles"> //Task would be accesible from Groovie by this name
<echo message="ANT_HOME is set to = ${basedir}" />
<taskdef name="ftp" classname="org.apache.tools.ant.taskdefs.optional.net.FTP">
<classpath>
<pathelement location="${basedir}/antlibs/ant-commons-net.jar" />
<pathelement location="${basedir}/antlibs/commons-net-3.0.1.jar" />
<pathelement location="${basedir}/antlibs/jakarta-oro-2.0.8.jar" />
</classpath>
</taskdef>
<ftp server="staging.oggifinogi.com" userid="administrator" password="xxx" port="21" remotedir="/components" passive="yes" binary="no">
<fileset dir="min/">
<include name="*.min.js" />
</fileset>
</ftp>
</target>
</project>
Let`s add last line of code to build script, it will load all files with *.min.js mask to FTP:
ant.importBuild 'deploy.xml'
And executing gradle buildscript from console:
gradle -b=core.gradle combineJs minifyJs deployFiles
Voila, JavaScript files are combined, minified and uploaded to server. Now you have more time for coding.[:]
У гредла есть возможности работы с ftp зачем ещё и антовые таски тащить в проект? Если уж без них совсем никак, то можно в скрипте гредла написать по антовски таску и не нужно создавать лишние файлы на диске и конфьюзить программистов
Спасибо. Не уверен, что в начале 2012 эта возможность была, однако в любом случае стоит поправить.