How can I write a gradle build task that runs a script such as "npm install" in a different directory than my gradle build file?

Viewed 1709

In a single project, I have two folders, project/server and project/web.

project/server is the root of my spring boot app with my build.gradle.kts file, while project/web is a react app with my package.json scripts, such as npm start. I would like to make a custom gradle task that runs "npm install" and "npm start" in the project/server folder, but I'm having trouble writing this task.

I have been following: https://karl.run/2018/05/07/kotlin-spring-boot-react/ and am getting tripped up at the part of the tutorial that says to run:

// Task for installing frontend dependencies in web
task installDependencies(type: NpmTask) {
    args = ['install']
    execOverrides {
        it.workingDir = '../web'
    }
}

// Task for executing build:gradle in web
task buildWeb(type: NpmTask) {
    args = ['run', 'build:gradle']
    execOverrides {
        it.workingDir = '../web'
    }
}

// Before buildWeb can run, installDependencies must run
buildWeb.dependsOn installDependencies

// Before build can run, buildWeb must run
build.dependsOn buildWeb

I can't use these snippets as they aren't getting recognized with Kotlin.

1 Answers

This is the script converted to Kotlin DSL:

import com.moowork.gradle.node.npm.NpmTask

// Task for installing frontend dependencies in web
val installDependencies by tasks.registering(NpmTask::class) {
    setArgs(listOf("install"))
    setExecOverrides(closureOf<ExecSpec> {
        setWorkingDir("../web")
    })
}

// Task for executing build:gradle in web
val buildWeb by tasks.registering(NpmTask::class) {
    // Before buildWeb can run, installDependencies must run
    dependsOn(installDependencies)

    setArgs(listOf("run", "build:gradle"))
    setExecOverrides(closureOf<ExecSpec> {
        setWorkingDir("../web")
    })
}

// Before build can run, buildWeb must run
tasks.build {
    dependsOn(buildWeb)
}
Related