본문 바로가기
Frontend

[Frontend 성능 개선] 프론트엔드 번들 크기를 최적화 주요 방법

by BenKangKang 2025. 2. 10.

1. 코드 분할 (Code Splitting)
```javascript
// 라우트 기반 분할
const Dashboard = lazy(() => import('./Dashboard'));

// 컴포넌트 기반 분할
const HeavyComponent = lazy(() => import('./HeavyComponent'));
```

2. Tree Shaking 활용
```javascript
// Bad
import _ from 'lodash'

// Good
import { map, filter } from 'lodash'
// 더 좋음
import map from 'lodash/map'
import filter from 'lodash/filter'
```

3. 이미지 최적화
```javascript
// Next.js Image 컴포넌트 사용
import Image from 'next/image'
import myImage from './my-image.jpg'


  src={myImage}
  placeholder="blur"
  width={500}
  height={300}
  alt="description"
/>
```

4. 번들 분석 도구 사용
```bash
# webpack-bundle-analyzer 설치
npm install --save-dev webpack-bundle-analyzer

# package.json에 스크립트 추가
"analyze": "ANALYZE=true next build"
```

5. CSS 최적화
```javascript
// CSS 모듈 사용
import styles from './Button.module.css'

// Tailwind CSS purge 설정
module.exports = {
  purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
  // ...
}
```

6. 외부 라이브러리 대체 검토
```javascript
// 예: Moment.js -> Day.js
// Before: 231.7KB
import moment from 'moment'

// After: 2.9KB
import dayjs from 'dayjs'
```

7. Dynamic Import 사용
```javascript
// 필요할 때만 로드
const MyChart = dynamic(() => import('react-chartjs-2'), {
  loading: () => 

Loading Chart...

,
  ssr: false
})
```

8. 캐싱 전략
```nginx
# Nginx 캐싱 설정
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires 1y;
    add_header Cache-Control "public, no-transform";
}
```

9. 성능 모니터링 도구 활용
```javascript
// web-vitals 설치
import { getCLS, getFID, getLCP } from 'web-vitals';

function sendToAnalytics({ name, delta, id }) {
  // 메트릭을 분석 서비스로 전송
}

getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getLCP(sendToAnalytics);
```

실제 적용 우선순위:
1. 가장 먼저 webpack-bundle-analyzer로 큰 번들 파일 식별
2. 코드 분할과 지연 로딩 적용
3. 무거운 라이브러리 최적화 또는 대체
4. 이미지와 assets 최적화
5. Tree Shaking 적용
6. 캐싱 전략 구현

댓글