처음 글 올리네요. ㅎㅎ
Spring boot에서 Tailwind CSS를 사용하고 싶어서 다음과 같은 방식을 고안하게 되었습니다.
저는 템플릿을 Thymeleaf(타임리프)를 좋아해서 이 기준으로 작성하겠습니다.
Framework : String boot 4
Template : Thymeleaf(타임리프)
CSS : Tailwind CSS
미리 Node.js 설치해 주세요.
우선 프로젝트 하나를 생성합니다.


그 다음 리소스를 생성합니다.
우선 index.html 을 다음과 같은 내용으로 생성합니다.
경로 : src/main/resources/template/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tailwind TEST</title>
</head>
<body>
<div>Tailwind CSS</div>
</body>
</html>
그 다음 스타일 시트를 생성합니다.
우선 스타일시트 파일 확인용이라 아무 스타일이나 입력해주세요.
경로 : src/main/resources/static/css/default.css
@charset "UTF-8";
html, body {
height: 100%;
place-items: center; place-self: center; place-content: center;
}
div {
width: 10rem; height: 5rem;
margin: 0 auto;
background: lightcoral;
border: 1px red solid;
}

그럼 두 경로에 파일이 보이실 꺼에요.
그다음 index.html head에 다음 테그를 삽입해 주세요.
<link rel="stylesheet" href="./../static/css/default.css">
스타일이 적용되는지 확인합니다.

적용 확인이 되면 그다음 head에 다음 tag를 삽입해 주세요.
<!-- Tailwind CSS dynamic Style CDN 스타일 완성후 삭제 -->
<script src="https://unpkg.com/@tailwindcss/browser@4"></script>
개발자 모드를 활용해 실시간으로 스타일이 적용되는지 확인해주세요.
확정 된 스타일을 index.html파일에 적용합니다.
이런 식으로 스타일을 적용하여 완성된 스타일을 default.css로 빌드하여 적용해 보도록 하겠습니다.
src랑 같은 위치에 node 경로를 생성해주세요.

그 다음 node안에 package.json 파일 생성 후 다음 내용을 입력해 주세요.
{
"dependencies": {
"@tailwindcss/forms": "^0.5.6",
"autoprefixer": "^10.4.16",
"fs-extra": "^11.1.1",
"heroicons": "^2.0.18",
"postcss": "^8.4.31",
"tailwindcss": "^3.3.3",
"update-browserslist-db": "^1.2.3"
}
}
터미널에서 다음 명령을 실행하세요.
npm install

빌드를 정상적으로 실행하기 위해 postcss 설정 파일을 생성합니다.
node/postcss.config.js
module.exports = {
plugins: [
require('tailwindcss'),
require('autoprefixer'),
]
}

이제 node안에 css파일을 하나 생성합니다.
node/default.css
아래의 내용을 추가합니다.
@tailwind base;
@tailwind components;
html, body {
@apply h-full place-items-center place-self-center place-content-center;
}
div {
@apply w-[10rem] h-[5rem] mx-auto rounded shadow-lg shadow-black/15
bg-red-200 text-center place-content-center
}
다음으로 할 작업은 nodejs 빌드 스크립트 추가입니다.
저는 node폴더에서 실행하는 기준으로 작성하겠습니다.
우선 빌드 대상은 node안에 있어야 함으로 node/tmpl 에 복사하고 빌드하도록 하겠습니다.
우선 node/tmpl 에 복사하는 스크립트를 작성하겠습니다.
node/copy.js 파일을 생성합니다.
const fsExtra = require('fs-extra');
console.log('Resource init!');
const sourceDirectory1 = './../src/main/resources/templates'; // 원본 디렉토리 경로
const targetDirectory1 = './tmpl/t'; // 대상 디렉토리 경로
console.log('Try copy '${sourceDirectory1}' -> ${targetDirectory1}');
fsExtra.copy(sourceDirectory1, targetDirectory1, err => {
if (err) {
console.error('Error copying directory:', err);
} else {
console.log('Directory copied successfully! 1');
}
});
console.log('Finished : ${new Date().toISOString()}');
그 다음 터미널에서 실행해 복사를 확인합니다.
node copy.js

index.html에서
<script src="https://unpkg.com/@tailwindcss/browser@4"></script>
를 삭제하고 정합니다.
다음은 tailwindcss 빌드 입니다.
-i : 인풋
-o : 아웃풋
터미널에서 아래 명령을 실행헤 주세요.
npx tailwindcss build -i default.css -o ../src/main/resources/static/css/default.css
그 다음 적용여부를 확인하면 완료입니다.

그리고 빌드를 쉽게 하기 위해 package.json의에 빌드 스크립트를 추가합니다.
빌드 대상 폴더 비우기
rm -rf tmpl
빌드 대상 복사
node copy.js
tailwindcss 빌드
tailwindcss build -i default.css -c tailwind.config.js -o
압축버전 빌드 (공백 삭제 등 용량 최적화)
--minify 추가
{
"scripts": {
"css": "rm -rf tmpl && node copy.js && tailwindcss build -i default.css -c tailwind.config.js -o ../src/main/resources/static/assets/v2/css/default.css",
"css-min": "rm -rf tmpl && node copy.js && tailwindcss build --minify -i default.css -c tailwind.config.js -o ../src/main/resources/static/assets/v2/css/default.css"
},
"dependencies": {
"@tailwindcss/forms": "^0.5.6",
"autoprefixer": "^10.4.16",
"fs-extra": "^11.1.1",
"heroicons": "^2.0.18",
"postcss": "^8.4.31",
"tailwindcss": "^3.3.3",
"update-browserslist-db": "^1.2.3"
}
}
이렇게 하면 빌드 시 아래화 같이 커맨드를 입력하면 됩니다.
일반 : npm run css
압축 : npm run css-min
gradle에서 빌드 시 위 내용을 자동 실행 하고 싶으면 build.gradle 다음 내용을 추가하면 됩니다.
task nodePreBuild(type: Exec) {
// node 폴더 위치를 절대 경로로 계산
workingDir = file("${projectDir}/node")
// Windows와 Mac/Linux 호환성 처리
if (System.getProperty('os.name').toLowerCase().contains('windows')) {
executable 'cmd'
args '/c', 'npm', 'run', 'css'
} else {
executable 'sh'
args '-c', 'npm run css'
}
// 3. 디버깅을 위한 출력 (Gradle 실행 시 콘솔에 찍힘)
doFirst {
println "--------- CSS Build Start ---------"
println "Working Directory: ${workingDir}"
println "Executable: ${executable}"
println "Arguments: ${args}"
println "-----------------------------------"
}
}
processResources.dependsOn nodePreBuild
궁금하신건 댓글 달아주세요.
Tailwind CSS 좋아하는데…
요즘 많이 힘들다고 하네요.
많이 응원해주세요. ㅎㅎ