프론트엔드 빌드 도구 Vite로 마이그레이션하기
@는 경로 별칭(alias)으로, 일반적으로 src 디렉토리를 의미하도록 설정하는 Webpack이나 Vite의 설정이다.
// 복잡한 상대 경로
import Button from '../../../../components/ui/Button';
// 단순한 절대 경로
import Button from '@/components/ui/Button';
이를 사용하는 이유는 폴더 이동 시 상대 경로는 전부 바꿔야 하지만 @를 쓰면 영향을 덜 받는다.
이 방식은 자주 사용되고 있고 컴포넌트 수가 많아질수록 효과가 커진다.
| Vite
Vite는 차세대 프론트엔드 빌드 도구로, 기존의 Create React App 보다 훨씬 빠른 개발환경과 최적화된 번들링을 제공한다.
/ React 프로젝트를 새로 시작할 경우
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
/ 기존 프로젝트에 Vite를 적용할 경우
현재까지 작업한 프로젝트를 백업해 둔 후 아래 순서를 따른다. 작업중 오류나 구조 변경이 생길 수 있어 원본을 보존하는 것이 안전하다.
1) 기존 CRA 프로젝트 정리
기존의 사용하던 CRA의 react-scripts와 관련 설정을 제거한다.
npm uninstall react-scripts
2) Vite 관련 패키지 설치
npm install --save-dev vite @vitejs/plugin-react
3) vite.config.js 생성
루트 경로에 vite.config.js 파일을 생성하고 아래 코드를 넣는다.
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
server: {
port: 3000,
},
});
4) package.json 수정
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
/ index.html
frontend/public/index.html 위치에서 frontend/index.html로 이동하는데 Vite형식에 맞게 파일을 새로 작성한다.
CRA는 public/index.html 경로에 사용하고 Vite는 루트 폴더에 index.html파일을 직접 둔다.
CRA에서 Vite로의 마이그레이션 방법은 기존 CRA 프로젝트를 직접 변환하는 방식과, 새로운 Vite 프로젝트를 만들어서 코드를 옮기는 방식, 크게 두 가지가 있다. 위의 방식은 빠른 변환이 가능하지만 설정 충돌이나 불필요한 파일이 남을 수 있어 프로젝트에는 새 Vite프로젝트를 만들어 코드를 옮기는 방식을 사용하려한다.
| 프로젝트에 Vite 마이그레이션
1) 프로젝트 백업
기존에 작업한 프로젝트 전체를 백업해 둔 후 시작한다.
2) vite 프로젝트 생성 및 초기화
루트에 backend와 frontend 디렉터리가 있을텐데 여기에 추가로 frontend-vite를 만들어 그 안에 vite를 설치하면 된다.
npm create vite@latest
이 명령어를 실행하면 project name, framework, variant를 설정하는데 프로젝트 이름은 원하는 이름을 적으면되고,
프레임워크는 React, Variant는 JavaScript를 선택한다.
설치가 끝나면 npm install을 해야 한다. package.json 파일은 만들어지지만 그 안에 명시된 의존성은 실제로 설치되지 않기 때문에 Vite를 실제로 실행하려면 npm install이 필요하다.
npm install
3) Tailwind CSS 설정
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
4) tailwind.config.js 수정
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
5) src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;
6) 기존 CRA 코드 복사
기존 프로젝트에서 src 폴더와 public 폴더를 새프로젝트로 복사한다.
기존의 CRA 기반 frontend는 그대로 두고서 새로만든 frontend-vite에 src, public 같은 코드를 새 구조로 옮기는 것이다.
<폴더 구조>
your-project/
├── backend/ # 기존 백엔드
├── frontend/ # 기존 CRA 백업
├── frontend-vite/ # ✅ 새 Vite 프론트엔드
│ ├── public/ # CRA에서 복사
│ ├── src/ # CRA에서 복사
│ ├── main.jsx ✅ 새로 작성
│ ├── App.jsx
│ └── index.css
│ ├── index.html # ✅ 새로 작성
│ ├── .env # ✅ 새로 작성
│ ├── vite.config.js # ✅ 새로 작성
│ ├── tailwind.config.js # (Tailwind 쓰는 경우)
│ └── package.json
7) index.html, main.jsx, App.js
Vite는 index.html이 루트에 있고 엔트리 파일을 명시해야 한다.
frontend-vite /index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>My App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
frontend-vite /src/main.jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
frontend-vite /src/App.jsx
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import { AuthProvider } from './context/AuthContext';
import AppRoutes from './routes';
function App() {
return (
<AuthProvider>
<Router>
<AppRoutes />
</Router>
</AuthProvider>
);
}
export default App;
8) vite.config.js 설정
frontend-vite/vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'), // @ → src 경로 별칭
},
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:5000', // 백엔드 주소
changeOrigin: true,
secure: false,
},
},
},
});
9) 환경변수
Vite에서는 VITE_로 명시해야 한다.
.env
VITE_API_URL=http://localhost:5000
사용시
const API = import.meta.env.VITE_API_URL
10) 실행 테스트
npm run dev