Fixing the Spring Boot LiveReload Server with Gradle for Thymeleaf and TailwindCSS
Thomas Schühly
Posted on July 5, 2022
LiveReloading with Thymeleaf
I couldn't get Live Reload with Spring Boot and Thymeleaf to work. The problem seems to be so widespread that even @wimdeblauwe the author of Taming Thymeleaf uses gulp/npm to get Live Reloading working.
I thought why do we need to use Javascript to get our Spring Boot Developer Experience up to par with the big Javascript Frameworks? We have a perfectly fine Build Tool with Gradle!
LiveReload.js
First we need to include a script tag which points to the LiveReload Server:
<script src="http://localhost:35729/livereload.js"></script>
Gradle Sync
The plan is the same as with the npm scripts. Sync the templates into the build output so LiveReload triggers properly. This is done with the Gradle Sync Task:
// build.gradle.kts
tasks.register("sync"){
inputs.files("./src/main/resources/static","./src/main/resources/templates",)
doLast {
sync {
from("./src/main/resources/static")
into("build/resources/main/static")
}
sync {
from("./src/main/resources/templates")
into("build/resources/main/templates")
}
}
}
Now start a continuous build with:
.\gradlew -t sync
Each time one of the inputs.files directory changes the sync task is rerun and LiveReload works.
Tailwind CSS
To use TailwindCSS we use the node-gradle plugin and create a npx task:
// build.gradle.kts
plugins {
...
id("com.github.node-gradle.node") version "3.4.0"
}
tasks.register<com.github.gradle.node.npm.task.NpxTask>("tailwind"){
command.set("tailwindcss")
args.set(listOf("-i", "./src/main/resources/static/styles.css",
"-o" ,"./src/main/resources/static/output.css", "--watch"))
}
We then need to create a package.json:
{
"devDependencies": {
"@tailwindcss/forms": "^0.5.2",
"tailwindcss": "^3.1.4"
}
}
Add a tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{html,js}"],
}
Add a styles.css in resources/static/:
@tailwind base;
@tailwind components;
@tailwind utilities;
and include output.css in our html:
<link href="/output.css" rel="stylesheet">
Now we can start the tailwind npx task in a new terminal:
.\gradlew tailwind
And it works:
You can see an example at: github.com/tschuehly/thymeleaf-livereload-gradle
Posted on July 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 5, 2022