본문 바로가기
IT개발/Spring Boot

(React + Typescript) + (Spring Boot + JPA + MySQL) 프로젝트 세팅 / tailwind css 설치 오류 포함

by 시간기억자 2025. 2. 12.
반응형

개인적으로 React + Typescript도 공부할겸, Spring Boot도 복습할 겸 맨땅에 헤딩을 하는 방법으로 무작정 프로젝트를 시작했다.

그런데 역시나 초기 세팅부터 이래저래 우여곡절이 많았다.

 

기존에는 백엔드 프로젝트를 할때 spring boot 프로젝트 만들고 프론트엔드 부분은 Thymeleaf를 주로 활용해서 intelliJ나 STS로 진행을 했었는데, 이렇게 프론트엔드 작업과 백엔드 작업을 한번에 하는 경우 프로젝트를 어떻게 세팅해야 할지 막막했다.

 

특히 React + Typescript는 기본 지식이 있는게 아니라 이번에 맨땅에 헤딩 하면서 공부할 생각이었기에 전적으로 chatGPT와 구글링의 도움이 필요했다.

 

그래서 지금 정리하는 아래의 방법이 일반적인 방법인지 솔지히 모르겠지만, 나는 일단 이렇게 일을 벌려놨으니 작업을 해보려 한다.


기본적인 프로젝트 구조

(깃허브 레파지토리)
└── 프로젝트 폴더
    ├── frontend ==> React + Typescript 설치(vite 활용)
    │   ├── node_modules
    │   ├── public
    │   ├── src
    │   │   ├── components
    │   │   ├── styles
    │   │   └── index.tsx
    │   ├── package.json
    │   ├── vite.config.ts
    │   └── index.css
    └── backend ==> Spring Boot 세팅
        ├── src
        │   ├── main
        │   │   └── java
        │   │       └── com
        │   │           └── example
        │   │               ├── controllers
        │   │               ├── models
        │   │               └── services
        │   ├── resources
        │   │   └── application.properties
        ├── pom.xml (또는 build.gradle)
        └── README.md

 

큰 틀에서 봤을때 하나의 프로젝트 안에서 frontend 작업과 backend 작업을 나눠서 진행하기 때문에 위와 같이 프로젝트 폴더 안에 frontend 폴더와 backend 폴더를 따로 만들어서 거기에 각각 필요한 세팅을 하는거라 생각하면 된다.

 

  • frontend : React + Typescript 설치(vite 활용)
  • backend : Spring Boot 세팅

🌟 프론트엔드(Frontend) - React + TypeScript + Tailwind CSS

1️⃣ React 프로젝트 생성 (Vite 활용)

프로젝트 루트 디렉토리에서 실행:

cd 프로젝트_폴더
npm create vite@latest frontend --template react-ts

 

설치 완료 후 frontend 폴더로 이동하여 패키지 설치:

cd frontend
npm install

 

vite로 React+Typescript를 설치하면 위와 같은 화면으로 나온다.

 

2️⃣ Tailwind CSS 설치 및 설정

frontend 디렉토리에서 실행:

npm install -D tailwindcss postcss autoprefixer @tailwindcss/vite
npx tailwindcss init -p

 

tailwind.config.ts 수정:

export default {
  content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};

 

index.css에 Tailwind 추가:

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

 

vite.config.ts 설정:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";

export default defineConfig({
  plugins: [react(), tailwindcss()],
});

 


🔥 Tailwind CSS 설치 과정 중 이슈

일반적으로 chatGPT에서 알려준 방법(위에 언급된 방법)대로 terminal을 이용해 설치 명령어를 입력했다.

 

npm install -D tailwindcss postcss autoprefixer @tailwindcss/vite

처음에 이 명령어를 입력 후 설치가 잘 된거 같은데, 문제는

 

npx tailwindcss init -p

이 명령어를 입력하고나서 계속 에러가 발생했다.

 

[에러]

jeonghyoseogs-MacBook-Pro:frontend hyosukjung$ npx tailwindcss init -p
sh: tailwind: command not found

 

sh: tailwind: command not found 에러가 뜨는 것이다.

 

그래서 chatGPT에게 물어보니 설치 과정중 오류가 있었을 수 있다고 tailwind css를 지웠다가 재설치 하는걸 알려줬다.

근데 결과적으로 아무것도 통하지 않았다.

tailwind css도 지웠다가 다시 설치해보고, 캐시도 지워보고, 심지어 node_modules도 지웠다가 다시 설치했는데 계속 같은 오류가 발생했고 하루종일 같은 방법만 챗바퀴 돌고 해결을 못했었다.

 

심지어 사실은 원래 react 프로젝트를 [create-react-app]으로 설치했었는데 tailwind css 오류 잡느라고 다시 다 지우고 vite로 재설치 한것이다.

 

아무튼 계속 이 오류가 해결이 안되니 tailwind.config.ts 파일이 생성되지도 않고, 그렇다보니 chatGPT가 알려준 방법을 적용할수가 없었다.

 

그러다가 GPT가 알려준 방법 말고 그냥 Tailwind CSS에서 알려준 방법을 적용해보기로 했다.

https://tailwindcss.com/docs/installation/using-vite

 

Installing with Vite - Installation

Integrate Tailwind CSS with frameworks like Laravel, SvelteKit, React Router, and SolidJS.

tailwindcss.com

 

1) Tailwind CSS 설치
: tailwindcssnpm 을 통해 설치합니다 @tailwindcss/vite.

[terminal]

npm install tailwindcss @tailwindcss/vite

 

2) Vite 플러그인 구성

: @tailwindcss/viteVite 구성에 플러그인을 추가합니다 .

[vite.config.ts]

import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
  plugins: [
    tailwindcss(),
  ],
})

 

3) Tailwind CSS 가져오기

: @importTailwind CSS를 가져오는 CSS 파일에 을 추가합니다 .

[css]

@import "tailwindcss";

 

4) 빌드 프로세스 시작

: npm run dev파일 에 구성된 명령이나 해당 명령을 사용해 빌드 프로세스를 실행하세요 . package.json

[terminal]

npm run dev

 

5) HTML에서 Tailwind를 사용하기 시작

: 컴파일된 CSS가 포함되어 있는지 확인하세요 <head> (프레임워크가 이를 처리할 수도 있음) . 그런 다음 Tailwind의 유틸리티 클래스를 사용하여 콘텐츠에 스타일을 지정하세요.

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="/src/styles.css" rel="stylesheet">
</head>
<body>
  <h1 class="text-3xl font-bold underline">
    Hello world!
  </h1>
</body>
</html>

 

 

일단 이 과정을 하나씩 따라해보니 다행히 에러는 안났다.

사실 처음에 이 방법은 뭔가 그냥 html 파일 기준으로 적용하는 거라 생각해서 react 프로젝트는 뭔가 방법이 다를거라 생각해서 계속 chatGPT가 알려준 방법에 의존했던 부분이 있었는데, chatGPT가 알려주는 방법이 계속 똑같은 방법이 반복되다 보니 결국 지쳐서 이 방법으로 돌아와본 것이다.

(chatGPT 뿐만 아니라 구글링을 해도 tailwind.config.ts 파일 설정하는 과정이 있었는데, 나는 이 파일이 생성이 안되다보니 문제였다.)

 

무튼 나도 이 방법처럼 코드를 추가하고 tailwind css 적용이 되는지 샘플 코드를 넣어보니 일단 적용되는걸 확인했다.

 

[vite.config.ts]

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react(), tailwindcss()],
})

 

[index.css]

@import "tailwindcss";
@tailwind base;
@tailwind components;
@tailwind utilities;

:root {
  font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
  line-height: 1.5;
  font-weight: 400;

  color-scheme: light dark;
  color: rgba(255, 255, 255, 0.87);
  background-color: #242424;

  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

a {
  font-weight: 500;
  color: #646cff;
  text-decoration: inherit;
}
a:hover {
  color: #535bf2;
}

body {
  margin: 0;
  display: flex;
  place-items: center;
  min-width: 320px;
  min-height: 100vh;
}

h1 {
  font-size: 3.2em;
  line-height: 1.1;
}

button {
  border-radius: 8px;
  border: 1px solid transparent;
  padding: 0.6em 1.2em;
  font-size: 1em;
  font-weight: 500;
  font-family: inherit;
  background-color: #1a1a1a;
  cursor: pointer;
  transition: border-color 0.25s;
}
button:hover {
  border-color: #646cff;
}
button:focus,
button:focus-visible {
  outline: 4px auto -webkit-focus-ring-color;
}

@media (prefers-color-scheme: light) {
  :root {
    color: #213547;
    background-color: #ffffff;
  }
  a:hover {
    color: #747bff;
  }
  button {
    background-color: #f9f9f9;
  }
}

 

[App.tsx]

import { useState } from 'react'
// import reactLogo from './assets/react.svg'
// import viteLogo from '/vite.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    
    <>
     <div className="flex min-h-screen items-center justify-center bg-gray-100">
      <h1 className="text-4xl font-bold text-blue-500">
        Tailwind CSS 적용 확인!
      </h1>
    </div>
    </>
  )
}

export default App

 

[적용화면]

 

 

사실 지금 계속 오류를 경험하다가 어쩌다 적용이 된거같아 좀 찝찝하지만 일단 적용이 됐으니 작업을 시작해봐야겠다.



🔧 백엔드(Backend) - Spring Boot

1️⃣ Spring Boot 프로젝트 생성

Spring Initializr(https://start.spring.io)를 활용(나는 gradle 선택)

 

2️⃣ application.properties 설정 (MySQL 기준)

spring.application.name=portfolio-2025

pring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/portfolio_project?useSSL=false&serverTimezone=UTC
spring.datasource.username=[본인 DB username]
spring.datasource.password=[본인 DB password]

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

#logging
logging.level.root=info

#devtools
spring.devtools.restart.enabled=true
spring.devtools.livereload.enabled=true

⚠️ 데이터베이스 설정 주의: 본인의 환경에 맞게 수정해야 합니다.

 

 

(일단 현재 나는 여기까지 세팅을 해놨고, 아래 프론트 백엔드 연결은 chatGPT에서 알려준걸 정리해둔다.)



(여기부터는 또 추후 맨땅에 헤딩하면서 확인해보는걸로..!)

🔗 프론트엔드와 백엔드 연결 (CORS 설정)

1️⃣ 백엔드에서 CORS 설정 추가

src/main/java/com/example/config/WebConfig.java 파일을 생성하고 아래 내용을 추가합니다:

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:5173");
            }
        };
    }
}

 

2️⃣ Vite Proxy 설정 (추천)

CORS 설정 없이 프록시를 사용하여 API 요청을 우회할 수도 있습니다.

vite.config.ts 수정:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:8080",
        changeOrigin: true,
        secure: false,
      },
    },
  },
});

 

이제 프론트엔드에서 API 호출 시 http://localhost:8080/api 대신 /api를 사용하면 자동으로 백엔드로 요청이 전달됩니다.

 


🏁 프로젝트 실행 및 테스트

1️⃣ 백엔드 실행 (Spring Boot)

cd backend
./mvnw spring-boot:run

 

2️⃣ 프론트엔드 실행 (React + Vite)

cd frontend
npm run dev

 

3️⃣ API 호출 테스트 (React에서 백엔드 연결)

src/App.tsx 파일 수정:

//[CORS 방법]

import { useEffect, useState } from "react";

function App() {
  const [message, setMessage] = useState("");

  useEffect(() => {
    fetch("http://localhost:8080/api/hello")
      .then((response) => response.text())
      .then((data) => setMessage(data));
  }, []);

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-100">
      <h1 className="text-4xl font-bold text-blue-500">{message}</h1>
    </div>
  );
}

export default App;
//[vite + Proxy 방법]

fetch("/api/hello")
  .then(response => response.text())
  .then(data => console.log(data));

 

브라우저에서 확인:

  • http://localhost:5173에 접속하여 Spring Boot에서 반환한 메시지가 정상적으로 출력되는지 확인합니다.
반응형

댓글