Skip to content

Spring Boot with Thymeleaf and Tailwind CSS - Complete Guide

Published on
  • Spring Boot
  • Thymeleaf
  • Tailwindcss

This is a step-by-step guide on how to integrate Tailwind CSS with Spring Boot and Thymeleaf.

It assumes that:

  • project is built with Maven
  • Node & NPM installed

It uses paseq-maven-plugin to orchestrate build process and local development workflow.

What is Tailwind CSS?

Have you heard about Tailwind CSS? Just in case you haven't - it is a modern, utility-first CSS framework. Long story short - it makes you express styling with ready to use CSS classes in HTML file instead of writing your own CSS. As a result it promises rapid website development and much less hassle and efforts with the maintenance.

Practically speaking it means that you can build complex, great looking websites/components:

  • without leaving HTML code
  • without being good in CSS (that's me)
  • without writing (almost) any CSS

For example such code:

html
<div class="my-4 md:w-1/3 rounded">
  <div class="flex items-start rounded-lg shadow-lg bg-white p-4">
    <div class="flex h-12 w-12 items-center justify-center rounded-full border border-blue-200 bg-blue-100">
      <svg ...>
        <!-- skipped for clarity -->
      </svg>
    </div>

    <div class="ml-4">
      <h2 class="font-semibold text-md">574 Messages</h2>
      <p class="mt-2 text-sm text-gray-500">Last opened 4 days ago</p>
    </div>
  </div>
</div>

Produces following component:

574 Messages

Last opened 4 days ago

Since components are self-contained within the HTML code, you can easily copy & paste them between projects without worrying if it does not affect other styles.

There are bunch of websites where you can find ready to use components, starting from the official component library made by Tailwind CSS authors: tailwindui.com.

Challenges with integrating Tailwind into Spring Boot project

The simplest way to integrate Tailwind with Spring Boot is just to add a link the CSS file with Tailwind classes in <head> part of the HTML. This comes with drawbacks:

Tailwind should run through NPM or the Tailwind CLI - and generate the final CSS file during the build time rather than the runtime. This means that we need to integrate Maven/Gradle workflow with NPM workflow for both building the application and running application in the development mode.

For that we are going to use paseq-maven-plugin that simplifies defining sequences of commands to be executed with Maven.

Generate Spring Boot & Thymeleaf project

Go to https://start.spring.io, choose Maven as a project type and add web, thymeleaf and devtools dependencies.

You should have directory structure like this:

├── HELP.md
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── example
        │           └── demo
        │               └── SpringTailwindApplication.java
        └── resources
            ├── application.properties
            ├── static
            └── templates

With following dependencies in pom.xml:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
</dependency>

Configure Tailwind CSS

Since frontend resources must be processed during the build time it is not a good idea to put them to src/main/resources. Instead, create a directory src/main/frontend and we are going to configure npm to generate final resources into src/main/resources directory

Create the most basic package.json file in src/main/frontend:

json
{
  "name": "frontend",
  "private": true
}

Install Tailwind CSS with:

bash
$ npm install --save-dev tailwindcss

It will automatically add tailwindcss to devDependencies section in package.json:

json
{
  "name": "frontend",
  "private": true,
  "devDependencies": {
    "tailwindcss": "^3.2.2"
  }
}

Create tailwind.config.js in src/main/frontend:

js
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["../resources/templates/**/*.{html,js}"], // it will be explained later
  theme: {
    extend: {},
  },
  plugins: [],
}

Pay special attention to the content property.

And finally, create a CSS file main.css also in src/main/frontend with following content:

css
@tailwind base;
@tailwind components;
@tailwind utilities;

Configure NPM scripts to compile CSS from src/main/frontend/main.css into a CSS file without any magic in src/main/resources/static/main.css.

Add scripts/build to package.json that invokes tailwindcss command:

json
{
  "name": "frontend",
  "private": true,
  "scripts": {
    "build": "tailwindcss -i ./main.css -o ../resources/static/main.css"
  },
  "devDependencies": {
    "tailwindcss": "^3.2.2"
  }
}

Now run npm run build to try it out and a file in src/main/resources/static/main.css will be created.

When you take a look at what got generated, you won't find much! There are no Tailwind utility classes there, just a bunch of CSS that effectively do CSS reset - wipe out the default browser styles. Why is that so and how does it work? Let's add a HTML file with Thymeleaf to find out.

Create a HTML template file with Thymeleaf

Create a file index.html in src/main/resources/templates/:

html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <!-- this is where we refer the css file from src/main/resources/static/main.css -->
    <link th:href="@{/main.css}" rel="stylesheet" /> 
</head>
<body>
    <h1 class="mt-2 text-xl" th:text="'Hello!'" />
</body>
</html>

Now when you run npm run build again, you will see that CSS classes references in the index.html file have been added to the output main.css file.

Because the content property in tailwind.config.js points to a directory with thymeleaf templates, Tailwind knows which classes are used in the application and includes only those in the output file. Pretty cool, right?

Configure Maven build workflow

We have all the pieces working, now we need to put it together. To build application following steps must be executed:

  1. Run npm install to download Tailwind CSS (and potentially other dependencies)
  2. Run npm build to process CSS files with Tailwind
  3. Run regular Java compilation and application packaging

We are going to use paseq-maven-plugin and configure it to run npm install and then npm run build in Maven compile phase:

xml
<build>
    <!-- ... -->
    <plugins>
        <!-- ... -->
		<plugin>
			<groupId>com.maciejwalkowiak.paseq</groupId>
			<artifactId>paseq-maven-plugin</artifactId>
			<version>0.1.1</version>
			<!-- configuration for building the package -->
			<executions>
				<execution>
					<phase>compile</phase>
					<goals>
						<goal>exec</goal>
					</goals>
					<configuration>
						<tasks>
							<task>
								<exec>
									<directory>src/main/frontend</directory>
									<command>npm install</command>
								</exec>
							</task>
							<task>
								<exec>
									<directory>src/main/frontend</directory>
									<command>npm run build</command>
								</exec>
							</task>
						</tasks>
					</configuration>
				</execution>
			</executions>
		</plugin>
    </plugins>
</build>

Now you can simply run:

bash
$ ./mvn verify # (or mvn clean install 🤪)

and get both, CSS classes processed and Java application built.

Note - it assumes that Node is installed on the machine.

Configure local development workflow

Configure a new NPM task - watch - that will continuously watch main.css file and trigger CSS processing as soon as it changes. Don't specify the output file as watch will be invoked twice to achieve live reload.

json
{
  "name": "frontend",
  "private": true,
  "scripts": {
    "build": "tailwindcss -i ./main.css -o ../resources/static/main.css",
    "watch": "tailwindcss -i ./main.css --watch"
  },
  "devDependencies": {
    "tailwindcss": "^3.2.2"
  }
}

The dev mode contains following steps:

  1. Run npm install to download Tailwind CSS (and potentially other dependencies)
  2. Run Tailwind CLI in a watch mode to continuously process CSS files on change
  3. Run backend with ./mvn spring-boot:run
xml
<plugin>
    <groupId>com.maciejwalkowiak.paseq</groupId>
    <artifactId>paseq-maven-plugin</artifactId>
    <version>0.1.0</version>
    <!-- configuration for building the package -->
    <executions>
		<execution>
		    <phase>compile</phase>
			<!-- ... this execution stay as it was -->
        </execution>
        <execution>
            <id>dev</id>
			<!-- configuration for running in dev mode with ./mvnw paseq:exec@dev -->
			<configuration>
				<tasks>
					<!-- first run npm install -->
					<task>
						<exec>
							<directory>src/main/frontend</directory>
							<command>npm install</command>
						</exec>
					</task>
					<!-- then start watch task in the background and output the result to `src/main/resources/static/main.css` -->
					<task>
						<async>true</async>
						<exec>
							<directory>src/main/frontend</directory>
							<command>npm run watch -- -o ../resources/static/main.css</command>
						</exec>
					</task>
					<!--
                    optionally post-processed CSS file can also be generated in `target` directory.
                    Changes to main.css will trigger live reload without a need to recompile the project in Intellij IDEA
                    -->
					<task>
						<async>true</async>
						<exec>
							<directory>src/main/frontend</directory>
							<command>npm run watch -- -o ${project.build.directory}/classes/static/main.css</command>
						</exec>
					</task>
					<task>
						<goals>spring-boot:run</goals>
					</task>
				</tasks>
			</configuration>
        </execution>
    </executions>
</plugin>

Run ./mvnw paseq:exec@dev to start application in the development mode and go to http://localhost:8080

Start using Tailwind CSS in your project

Start using Tailwind utility classes in Thymeleaf templates. Note that if you use Intellij IDEA, once you modify the template file you must trigger the project build.

Configure custom CSS in src/main/frontend/main.css. For example:

css
@tailwind base;
@tailwind components;
@tailwind utilities;

.my-header {
    @apply text-2xl my-4 mx-4
}

Whenever you hit Save (CMD+S/CTRL+S) in Intellij IDEA, you only need to refresh the browser to see the changes.

Live Reload

Spring DevTools integrates with Live Reload Browser Extension. Once the extension is active, you don't need to refresh the browser manually as Spring DevTools will trigger the extension to reload the page automatically when CSS file changes.

Alternative Approaches

If for any reason the approach presented above does not meet your needs, Wim Deblauwe - a Thymeleaf expert - described multiple ways of integrating Tailwind into a Spring Boot application:

Conclusion

I hope following this guide helped you to get Tailwind CSS working in a Spring Boot application. If you encountered any problems - please leave a comment below. Also check please a sample project on GitHub - sometimes it is easier to just copy & paste from the final project than following the tutorial.

👉 https://github.com/maciejwalkowiak/spring-boot-thymeleaf-tailwindcss-sample

Let's stay in touch and follow me on Twitter: @maciejwalkowiak

Subscribe to RSS feed