I'm trying to build and pack a react app with my spring backend (so they can be hosted together). I have the react app under src/main/js
and what I need to do is to build it then copy the contents of the build folder to resources/static
then copy the index.html from there to resources/templates
(so my main spring controller can serve it)
I have followed multiple tutorials in the topic and even though non of them worked completely, I've managed to come up with this solution (only adding the tasks part of my build.gradle.kts
:
val jsDir = "src/main/js"
val staticDir = "src/main/resources/static"
val templatesDir = "src/main/resources/templates"
tasks.register<YarnTask>("installDependencies") {
args.set(listOf("install"))
execOverrides.set {
setWorkingDir(jsDir)
}
}
tasks.register<YarnTask>("buildReact") {
dependsOn("installDependencies")
args.set(listOf("build"))
execOverrides.set {
setWorkingDir(jsDir)
}
}
tasks.register<Delete>("preCleanup"){
delete(staticDir)
delete(templatesDir)
mkdir(staticDir)
mkdir(templatesDir)
}
tasks.register<Delete>("cleanup"){
delete("$staticDir/index.html")
delete("$jsDir/build")
}
tasks.register<Copy>("copyBuild"){
dependsOn("buildReact")
from("$jsDir/build")
into(staticDir)
}
tasks.register<Copy>("copyTemplate"){
dependsOn("copyBuild")
from("$staticDir/index.html")
into(templatesDir)
finalizedBy("cleanup")
}
tasks.register<Task>("buildWeb"){
dependsOn("preCleanup")
finalizedBy("copyTemplate")
}
tasks.bootRun{
dependsOn("buildWeb")
}
(I'm using this Gradle Node plugin)
Looking at my files, the build is successful but when I navigate to the url of my app I either see an error page (on the first build) or the previous version of my react app. Almost seems like the bootRun
task saves the state of the files before running my tasks so it always gets the previous version of the react files
I could solve this problem by creating a new tasks that depends on my buildWeb
and is finalised by bootRun
but it would just be nicer if bootRun
could automatically do the job.
tasks.register<Task>("bootRunWithWeb"){
dependsOn("buildWeb")
finalizedBy("bootRun")
}
CodePudding user response:
bootRun has the main source set’s output on its classpath but you are copying things to one of its input locations. It is the processResources task that copied resources from the input location to the output location. If processResources runs before you add files to src/main/resources, the new files will be missed.
To fix this, you could either make processResources depend on buildWeb or you could copy the files into sourceSets.main.output.resourcesDir.