본문 바로가기
개발 팁

React + Vite 프로젝트 초기 세팅 — 매번 하는 것들 정리

by 루까(Luka) 2026. 2. 25.
반응형

새 프로젝트를 시작할 때마다 같은 설정을 반복한다. 검색하고 복붙하는 시간을 없애기 위해 한 곳에 정리해둔다.


1. 프로젝트 생성

npm create vite@latest my-app -- --template react
cd my-app
npm install

TypeScript를 쓴다면 --template react-ts로 바꾸면 된다.

생성 직후 폴더 구조:

my-app/
├── public/
├── src/
│   ├── assets/
│   ├── App.jsx
│   ├── App.css
│   ├── index.css
│   └── main.jsx
├── index.html
├── vite.config.js
└── package.json

App.cssindex.css는 보일러플레이트 스타일이 들어있다. Tailwind를 쓸 거라면 둘 다 지운다.


2. Tailwind CSS 설치

npm install tailwindcss @tailwindcss/vite

vite.config.js 수정:

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

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

src/index.css 내용을 전부 지우고 한 줄만 추가:

@import "tailwindcss";

App.css는 삭제하고, App.jsx에서 import './App.css' 줄도 제거한다.

정상 동작 확인

App.jsx에 Tailwind 클래스를 하나 넣어보고 스타일이 적용되면 완료다.

function App() {
  return (

      Tailwind 작동 확인

  )
}

3. 폴더 구조 정리

Vite 기본 구조는 컴포넌트가 늘어나면 금방 지저분해진다. 처음부터 잡아두는 게 편하다.

src/
├── components/       # 재사용 컴포넌트
│   ├── ui/           # 버튼, 인풋 등 기본 UI
│   └── layout/       # 헤더, 사이드바 등 레이아웃
├── pages/            # 라우트별 페이지
├── hooks/            # 커스텀 훅
├── api/              # API 호출 함수
├── utils/            # 유틸 함수
├── context/          # 전역 상태 (Context API)
├── assets/           # 이미지, 폰트
├── App.jsx
├── main.jsx
└── index.css

규모가 작은 프로젝트는 hooks/, context/는 필요할 때 추가해도 된다.


4. React Router 설치

npm install react-router-dom

main.jsx에 BrowserRouter 감싸기:

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import './index.css'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(




  ,
)

App.jsx에서 라우트 설정:

import { Routes, Route } from 'react-router-dom'
import Home from './pages/Home'
import About from './pages/About'

function App() {
  return (

      } />
      } />

  )
}

export default App

5. Axios 설치 및 기본 설정

npm install axios

src/api/axios.js 파일 생성:

import axios from 'axios'

const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:5001/api',
  timeout: 10000,
})

// 요청 인터셉터 — JWT 토큰 자동 첨부
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 응답 인터셉터 — 401 시 자동 로그아웃
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default api

컴포넌트에서는 이 api 인스턴스만 import해서 쓴다. axios 직접 import는 피한다.


6. 환경 변수 설정

.env 파일 생성 (프로젝트 루트):

VITE_API_URL=http://localhost:5001/api
VITE_GOOGLE_MAPS_KEY=your_key_here

Vite에서 환경 변수는 반드시 VITE_ 접두사가 붙어야 클라이언트에서 접근 가능하다.

// 코드에서 사용
const apiUrl = import.meta.env.VITE_API_URL

.gitignore에 반드시 추가:

.env
.env.local
.env.production

.env.example 파일도 함께 만들어두면 협업할 때 편하다:

VITE_API_URL=http://localhost:5001/api
VITE_GOOGLE_MAPS_KEY=

7. ESLint 설정 확인 및 조정

Vite가 기본으로 ESLint를 잡아주지만 몇 가지 규칙이 거슬리는 경우가 있다. eslint.config.js에서 조정한다.

자주 끄는 규칙:

// eslint.config.js
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'

export default [
  { ignores: ['dist'] },
  {
    files: ['**/*.{js,jsx}'],
    languageOptions: {
      ecmaVersion: 2020,
      globals: globals.browser,
    },
    plugins: {
      'react-hooks': reactHooks,
      'react-refresh': reactRefresh,
    },
    rules: {
      ...reactHooks.configs.recommended.rules,
      'react-refresh/only-export-components': 'warn',
      'no-unused-vars': 'warn',        // error → warn으로 완화
    },
  },
]

8. vite.config.js — 경로 별칭 설정

컴포넌트가 깊어지면 ../../components/Button 같은 상대 경로가 지저분해진다. 절대 경로 별칭을 잡아두면 편하다.

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

export default defineConfig({
  plugins: [react(), tailwindcss()],
  resolve: {
    alias: {
      '@': resolve(__dirname, './src'),
    },
  },
})

이후 import에서:

// 전
import Button from '../../components/ui/Button'

// 후
import Button from '@/components/ui/Button'

9. 최종 package.json scripts 확인

{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "lint": "eslint ."
  }
}

npm run dev로 개발 서버 실행, npm run build로 프로덕션 빌드 생성, npm run preview로 빌드 결과물 로컬 확인이 가능하다.


정리

단계 명령어 / 작업
프로젝트 생성 npm create vite@latest
Tailwind 설치 npm install tailwindcss @tailwindcss/vite
라우터 설치 npm install react-router-dom
Axios 설치 npm install axios
폴더 구조 components/, pages/, hooks/, api/, utils/
환경 변수 .env + VITE_ 접두사 + .gitignore 추가
경로 별칭 vite.config.js@ → src 설정

이 순서대로 한 번만 해두면 개발 시작부터 불필요한 삽질이 줄어든다.

 

반응형