TypeScript with Gradle

There’s two Gradle plugins on the market today that both promise TypeScript support:



Only problem is that they won’t work and their documentation sometimes lie with false examples, and more often, lack real information forcing you to study source code just to get a clue. Some problems I could work around but in the end, I never got any one of the plugins to actually work on my Windows machine using Gradle 2.3.6 (versions of the plugins tested is 1.0.6 and 2.2.4 respectively). Big big thank you to the authors of these plugins, but please improve the docs =)

Turns out it wasn’t so hard to put together a working TypeScript compilation task anyways. The benefit is not only that it work, you reduce the dependencies of your build script as well =) The following is the build task that I scrapped together today, but it isn’t much tested and I bet it isn’t without any flaws. So to serve as inspiration only:

task compileTs {
    def tsSrcDir = "$projectDir/src/main/ts"
    def tsBuildDir = "$buildDir/ts"
    def projectToSrc = projectDir.toPath()
    def projectToBuild = projectDir.toPath()
    group = 'build'
    description = "Compile TypeScript .ts file from \"$projectToSrc\" to \"$projectToBuild\"."
    // Support incremental builds:
    inputs.dir tsSrcDir
    outputs.dir tsBuildDir
    def tsc = {
        // What to execute:
        executable = 'tsc' // <-- TypeScript Compiler
        // Redirect output:
        standardOutput = System.out;
        // Which files to compile:
        def files = []
        file(tsSrcDir).eachFileRecurse groovy.io.FileType.FILES, {
            if (it.name.endsWith('.ts')) {
                files << it.absolutePath
        args files
    // compile
    doLast {
        exec tsc << { // <-- "tsc << {}" combines two closures into one

            // Outdir:
            args '--outDir'
            args "$tsBuildDir/compiled"
    // combine (put a "_references.ts" in root to more easily specify the dependency graph)
    doLast {
        exec tsc << {
            args '--out'
            args "$tsBuildDir/combined/${project.name}.js"

Leave a Reply

Your email address will not be published. Required fields are marked *