How to add TailWind CSS in Spring Boot Application
Overview
This post will describe the steps required to add tailwind css(v4) in spring boot project for server-side rendering.
Tailwind CSS is an amazing CSS utility tool which allows to add styling in web-pages without the need to write too much CSS code. It provides built-in utility classes that you can directly use to add stylings.
Pre-requisits:
You must have npm installed in order to use tailwind css.
Basic Setup
1. npm project initialization
First, we need to add npm packages in our spring boot project.
1. use following command to initialze npm package in spring boot project directory:
npm init -y
This will add package.json file into spring boot project directory.
2. use following command to add required tailwind packages into project(will create package.json file):
npm install tailwindcss @tailwindcss/cli
2. tailwindCSS Configurations:
Now that we have added required packages, let's add required configurations.
1. add following directives in your main CSS file(/resources/static/css/style.tailwind.css):
@import "tailwindcss";
These directives are used to generate CSS file.
3. Now, add following script in package.json file to copy generate tailwindCSS file in directoy environment:
"scripts": {
"build:tailwindcss": "npx @tailwindcss/cli -i src/main/resources/static/css/style.tailwind.css -o src/main/resources/static/css/style.build.tailwind.css --minify",
"watch:tailwindcss": "npx @tailwindcss/cli -i src/main/resources/static/css/style.tailwind.css -o src/main/resources/static/css/style.build.tailwind.css --watch"
},
},
Here, 'build:tailwindcss' script is used to build production tailwindcss file, whereas 'watch:postcss' file is used to run tailwindcss file in development mode. You will be prompted to install cli dependency in terminal.
4. Now, run the following scripts for development and production respectively in spring boot directory:
npm run watch:tailwindcss npm run build:tailwindcss
5. Add following line in html template(thymeleaf) to add CSS file(for non-thymleaf template, remove "th:" from link):
<link rel="stylesheet" th:href="@{/css/style.build.tailwind.css}">
Additonal Setup(if need arises)
1. Adding plugin
Let's say we wan to add daisy_ui plug-in into tailwindCSS.
1. Install dainsyUI by following command:
npm i -D daisyui@beta
2. Add following lines in style.tailwind.css file:
@plugin "daisyui";
That's it. You have now successfully added daisyUI plugin. Other plug-ins follow the same approach.
Updagrade existing tailwind version:
to upgrade existing tailwindcss, remove existing dependencies from package.json file, and repeat the steps from 2 of basic steps heading onwards