This is the 3rd and final part of my series on live reloading with Thymeleaf and Spring Boot, this time focusing on Tailwind CSS.
As an overview, these are the blog posts:
-
Thymeleaf live reload with Spring Boot and Tailwind CSS (This post)
|
If you like to use Gradle, you can also have a look at Fixing the Spring Boot LiveReload Server with Gradle for Thymeleaf and TailwindCSS by Thomas Schuehly. |
This post assumes you have a live reload setup as detailed in Thymeleaf live reload with npm scripts. If you want to add Tailwind CSS to it, you need to use a few special tricks. Not very difficult, but you just have to know it.
Follow these steps to get everything working:
-
Install Tailwind CSS into the project using
npm:npm install -D tailwindcss npx tailwindcss init -
That last command generates a
tailwind.config.js. Have thecontentpoint to the location of the Thymeleaf templates:/** @type {import('tailwindcss').Config} */ module.exports = { content: ['./src/main/resources/templates/**/*.html'], theme: { extend: {}, }, plugins: [], } -
Because Tailwind CSS only generates CSS for the classes you actually use in the HTML, we have to update our watch script to run the CSS build whenever the HTML changes. Update
watch:htmlinpackage.jsonlike this:"watch:html": "onchange 'src/main/resources/templates/**/*.html' -- npm-run-all --serial build:css build:html",Notice how we use
npm-run-allto run bothbuild:cssandbuild:htmlin serial. -
We also need to update
watch:servicewith the--no-inject-changesparameter:"watch:serve": "browser-sync start --no-inject-changes --proxy localhost:8080 --files 'target/classes/templates' 'target/classes/static'"Without that change, browser sync tries to somehow manually inject the CSS but that does not seem to work very well. By adding the parameter, a page refresh is done instead.
-
Update
application.cssto use the default Tailwind CSS setup:@tailwind base; @tailwind components; @tailwind utilities; -
Update
postcss.config.jsto use the Tailwind CSS plugin:const postcssConfig = { plugins: [ require('autoprefixer'), require('tailwindcss') ], }; ... -
Update
application-local.propertiesto ensure the CSS is not cached:spring.thymeleaf.cache=false spring.web.resources.chain.cache=false
To test it out:
-
Start the Spring Boot application with the
localprofile. -
Run
npm run build && npm run watchfrom the command line.
This will open your default browser at http://localhost:3000. Any edit to a HTML file or the CSS file should show up in your browser as soon as you save it.
Conclusion
This post showed how to add Tailwind CSS to your Spring Boot with Thymeleaf project.
See https://github.com/wimdeblauwe/blog-example-code/tree/master/live-reload-npm-scripts-tailwindcss] on GitHub for the full sources of this example.
If you have any questions or remarks, feel free to post a comment at GitHub discussions.