DevTools & Bundling
Chrome DevTools 마스터, 번들링 최적화, 그리고 Observability를 통해 시니어 프론트엔드 개발자의 필수 역량을 갖추세요.
Elements & Console 패널
DOM/CSS 디버깅과 강력한 Console 기능 마스터
Elements 패널 핵심 기능
DOM Inspection
HTML 구조 실시간 검사 및 수정
- →Elements 패널에서 노드 클릭으로 선택
- →우클릭 → "Edit as HTML"로 직접 수정
- →Delete 키로 요소 삭제, Ctrl+Z로 복원
- →Drag & Drop으로 DOM 순서 변경
Console 고급 기능
console.log 그 이상의 기능들
Console은 단순 로깅을 넘어 강력한 디버깅 도구입니다. $0, $1로 최근 선택 요소 참조, debug(fn)으로 함수 호출 시 자동 브레이크!
// console.table - 배열/객체를 테이블로 표시
const users = [
{ name: 'Alice', age: 25, role: 'Developer' },
{ name: 'Bob', age: 30, role: 'Designer' },
];
console.table(users);
// console.dir - DOM 요소의 속성 확인
console.dir(document.body);
// console.trace - 호출 스택 추적
function outer() {
function inner() {
console.trace('Call stack');
}
inner();
}
outer();
// %c 스타일 로그
console.log('%cWarning!', 'color: red; font-size: 20px');
// console.group - 로그 그룹화
console.group('User Info');
console.log('Name: Alice');
console.log('Age: 25');
console.groupEnd();Console 특수 명령어
$0, $1, $2...Elements에서 선택한 최근 요소들
$0.classList$$(selector)querySelectorAll의 축약형
$$("button")copy(object)객체를 클립보드로 복사
copy($0.outerHTML)debug(fn)함수 호출 시 자동 브레이크
debug(myFunction)monitor(fn)함수 호출 시 로그 출력
monitor(onClick)monitorEvents(el)요소의 모든 이벤트 로깅
monitorEvents($0, 'click')단축키 마스터
Sources & Network 패널
진짜 디버깅 실력과 네트워크 분석 능력 갖추기
Breakpoint 종류 마스터
디버깅 실력이 곧 실력이다
console.log로 디버깅하는 시대는 지났습니다. Breakpoint와 Step through를 활용하면 버그를 훨씬 빠르게 찾을 수 있습니다.
라인 브레이크포인트
특정 코드 라인에서 멈춤
디버깅 컨트롤
Resume
F8다음 브레이크포인트까지 실행
Step Over
F10현재 라인 실행, 함수 내부 안 들어감
Step Into
F11함수 내부로 진입
Step Out
Shift+F11현재 함수에서 나감
Pause
F8실행 중인 스크립트 일시정지
Restart
Ctrl+Shift+F8현재 함수 처음부터 다시
Scope & Watch
Scope 패널
- • Local: 현재 함수의 지역 변수
- • Closure: 클로저로 캡처된 변수
- • Global: window 객체의 속성들
Watch 패널
- • 특정 변수/표현식을 지속적으로 모니터링
- • user.profile?.name 같은 표현식 가능
- • 배열 길이, 객체 속성 등 실시간 추적
Network 패널 분석
네트워크 분석의 핵심
리소스 병목을 찾을 때 필수! TTFB, 페이로드 크기, 캐싱 정책을 확인하세요.
Headers
요청/응답 헤더 확인
Timing
요청 각 단계 시간 분석
Throttling
네트워크 속도 제한 테스트
Filter
리소스 타입별 필터링
비동기 스택 트레이스
Settings → Preferences → Async stack traces를 활성화하면 Promise, setTimeout, async/await의 전체 호출 스택을 추적할 수 있습니다. 비동기 버그 디버깅에 필수!
Performance & Memory 패널
렌더링 병목 분석과 메모리 누수 탐지
Performance 녹화 분석
성능 튜닝의 핵심 도구
Performance 패널은 프론트엔드 성능 최적화의 핵심 도구입니다. 프레임 분석, Long Task 탐지, 레이아웃 시프트 확인까지 모든 것이 가능합니다.
FPS
Frames Per Second - 초당 프레임 수
Performance 녹화 단계
녹화 시작
Ctrl+E 또는 Record 버튼 클릭
사용자 시나리오 실행
스크롤, 클릭, 입력 등 테스트할 동작 수행
녹화 중지
Stop 버튼 클릭 (5초 이내 권장)
프레임 차트 분석
Main 스레드에서 Long Task 확인
병목 지점 확대
빨간색/노란색 영역 클릭하여 상세 확인
Memory 패널 - 누수 탐지
메모리 누수는 SPA의 적
대규모 SPA에서 메모리 누수는 점점 앱을 느리게 만듭니다. Detached DOM nodes와 Heap snapshot으로 누수를 찾으세요.
Heap Snapshot
현재 메모리 상태 캡처
전후 비교로 누수 확인
Allocation Timeline
시간에 따른 할당 추적
어떤 동작이 메모리 증가시키는지
Allocation Sampling
함수별 메모리 할당량
비용이 큰 함수 식별
Detached Elements
DOM에서 분리된 노드들
이벤트 리스너 누수의 원인
흔한 메모리 누수 패턴
Event Listener 미해제
useEffect(() => { window.addEventListener(...); }, []);✓ 해결: cleanup 함수에서 removeEventListener
setInterval 미정리
setInterval(() => { ... }, 1000);✓ 해결: useEffect cleanup에서 clearInterval 호출
클로저가 DOM 참조 유지
const el = document.getElementById(...);✓ 해결: 필요 없으면 null 할당
구독 미해제
observable.subscribe(...);✓ 해결: unsubscribe in cleanup
번들링 이해 (Webpack/Vite/Rollup)
모던 프론트엔드 빌드 도구의 핵심 개념
번들러 비교
Webpack
장점
- ✓ 풍부한 생태계
- ✓ 세밀한 설정
- ✓ 검증된 안정성
단점
- ✗ 느린 빌드
- ✗ 복잡한 설정
- ✗ 러닝 커브
Webpack 핵심 개념
Entry
번들링 시작점
entry: "./src/index.js"Output
번들 출력 경로
output: { path, filename }Loaders
파일 변환기
babel-loader, ts-loaderPlugins
번들 최적화/변환
HtmlWebpackPluginMode
development/production
자동 최적화 설정DevServer
개발 서버 + HMR
webpack-dev-server// webpack.config.js 기본 구조
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
},
module: {
rules: [
{ test: /\.tsx?$/, use: 'ts-loader' },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
],
},
plugins: [
new HtmlWebpackPlugin({ template: './public/index.html' }),
],
optimization: {
splitChunks: { chunks: 'all' },
},
};Vite - 현대 프론트엔드 표준
왜 Vite인가?
Vite는 ES Modules를 활용해 번들 없이 개발 서버를 실행합니다. Webpack 대비 10-100배 빠른 Cold Start를 제공하며, 프로덕션 빌드는 Rollup을 사용합니다.
Vite vs Webpack 차이
Webpack (Bundle-based)
모든 모듈 → 번들 생성 → 서버 시작느린 Cold Start
Vite (ESM-based)
서버 시작 → 요청 시 모듈 변환즉각적인 시작
// vite.config.ts - 간결한 설정
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
},
},
},
},
});핵심 빌드 개념
트리 쉐이킹
사용하지 않는 코드를 번들에서 제거
💡 ES Modules + sideEffects: false 필요
코드 스플리팅
번들을 여러 청크로 분리
💡 dynamic import()로 구현
HMR (Hot Module Replacement)
전체 새로고침 없이 모듈만 교체
💡 개발 생산성 향상
Source Maps
번들된 코드를 원본에 매핑
💡 디버깅 필수, production에선 비활성화
번들 최적화 전략
번들 분석과 최적화로 성능 극대화하기
번들 분석기
번들 분석의 중요성
어떤 라이브러리가 번들을 비대하게 만드는지 시각화합니다. moment.js, lodash 전체 import 등 숨겨진 비용을 발견하세요.
// webpack-bundle-analyzer 설정
// webpack.config.js
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
}),
],
};
// Vite의 경우
// npm install -D rollup-plugin-visualizer
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig({
plugins: [visualizer({ open: true })],
});라이브러리 최적화
import _ from "lodash"import debounce from "lodash-es/debounce"import moment from "moment"import { format } from "date-fns"import * as Icons from "@heroicons/react"import { HomeIcon } from "@heroicons/react/24/solid"import Chart from "chart.js"import { Chart, registerables } from "chart.js"Dynamic Import (Code Splitting)
// Route-based Code Splitting
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));
function App() {
return (
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}
// Component-based Code Splitting
const HeavyChart = lazy(() => import('./components/HeavyChart'));
function Analytics() {
const [showChart, setShowChart] = useState(false);
return (
<div>
<button onClick={() => setShowChart(true)}>Show Chart</button>
{showChart && (
<Suspense fallback={<ChartSkeleton />}>
<HeavyChart />
</Suspense>
)}
</div>
);
}Best Practice: 라우트별 분할 + 조건부 렌더링 컴포넌트 분할을 조합하세요. 초기 번들 크기를 줄이고 필요할 때만 코드를 로드합니다.
sideEffects와 Tree Shaking
Tree Shaking이 안 되는 경우
CommonJS 모듈, side effects가 있는 코드, 또는 sideEffects 플래그가 없으면 Tree shaking이 작동하지 않습니다.
// package.json - sideEffects 설정
{
"name": "my-library",
"sideEffects": false, // 모든 모듈이 순수함
// 또는 특정 파일만 지정
"sideEffects": [
"*.css",
"*.scss",
"./src/polyfills.js"
]
}
// Tree shaking이 안 되는 패턴
import _ from 'lodash'; // ❌ 전체 import
import { map } from 'lodash'; // ❌ CommonJS라서 안 됨
// Tree shaking이 되는 패턴
import map from 'lodash-es/map'; // ✅ ES Module 개별 import
import { map } from 'lodash-es'; // ✅ ES Module최적화 체크리스트
Observability (에러 모니터링)
Sentry로 실서비스 에러 추적 및 성능 모니터링
왜 에러 모니터링이 필수인가?
프론트엔드 에러는 숨는다
프론트엔드 에러는 서버 로그에 남지 않습니다. 사용자가 "안 돼요"라고 할 때 이미 수많은 에러가 발생했을 수 있습니다. 실시간 에러 수집 시스템은 프로덕션 필수입니다.
Sentry 핵심 기능
에러 추적
JS 에러 자동 수집 및 분류
- →스택 트레이스 + 소스맵으로 원본 코드 위치 표시
- →에러 빈도, 영향받은 사용자 수 집계
- →Release별 에러 추적으로 회귀 감지
React 프로젝트에 Sentry 연동
// 1. 설치
npm install @sentry/react
// 2. 초기화 (main.tsx 또는 index.tsx)
import * as Sentry from "@sentry/react";
Sentry.init({
dsn: "https://xxx@xxx.ingest.sentry.io/xxx",
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration(),
],
tracesSampleRate: 1.0, // 성능 모니터링 샘플링
replaysSessionSampleRate: 0.1, // 일반 세션 10%
replaysOnErrorSampleRate: 1.0, // 에러 세션 100%
});
// 3. Error Boundary 래핑
const root = createRoot(document.getElementById('root')!);
root.render(
<Sentry.ErrorBoundary fallback={<ErrorFallback />}>
<App />
</Sentry.ErrorBoundary>
);
// 4. 수동 에러 캡처
try {
riskyOperation();
} catch (error) {
Sentry.captureException(error, {
tags: { feature: 'checkout' },
extra: { userId: user.id },
});
}Source Map 업로드
원본 코드 라인 표시
프로덕션 빌드는 minify되어 스택 트레이스가 읽기 어렵습니다. Source Map을 업로드하면 원본 파일명과 라인 번호가 표시됩니다.
// Vite 설정 (vite.config.ts)
import { sentryVitePlugin } from "@sentry/vite-plugin";
export default defineConfig({
build: {
sourcemap: true, // Source Map 생성
},
plugins: [
sentryVitePlugin({
org: "your-org",
project: "your-project",
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
});
// Webpack 설정
const SentryWebpackPlugin = require("@sentry/webpack-plugin");
module.exports = {
devtool: "source-map",
plugins: [
new SentryWebpackPlugin({
include: "./dist",
release: process.env.RELEASE_VERSION,
}),
],
};체계적인 로깅 구조
// Axios Interceptor로 체계적 로깅
import axios from 'axios';
const api = axios.create({ baseURL: '/api' });
// 요청 로깅
api.interceptors.request.use((config) => {
config.metadata = { startTime: Date.now() };
console.log(`[API] ${config.method?.toUpperCase()} ${config.url}`);
return config;
});
// 응답 로깅 + 에러 추적
api.interceptors.response.use(
(response) => {
const duration = Date.now() - response.config.metadata.startTime;
console.log(`[API] ${response.status} in ${duration}ms`);
return response;
},
(error) => {
Sentry.captureException(error, {
tags: {
api: error.config?.url,
status: error.response?.status,
},
});
// 자동 재시도 로직
if (error.response?.status === 503) {
return retryRequest(error.config);
}
return Promise.reject(error);
}
);모니터링 Best Practices
Release 태깅
버전별 에러 추적으로 회귀 감지
환경 분리
dev/staging/prod 환경별 필터링
알림 설정
Slack/Email 알림으로 즉시 대응
샘플링 조정
트래픽에 따라 샘플링 비율 조정
Issue 할당
팀원에게 자동 할당 규칙 설정
PII 마스킹
민감 정보 자동 필터링
Web Vitals 수집
실사용자 환경에서 성능 측정 및 개선
Core Web Vitals란?
Google의 성능 지표
Core Web Vitals는 LCP, INP, CLS 세 가지 지표로 구성됩니다. 실제 사용자 경험을 측정하며, SEO 랭킹에도 영향을 미칩니다.
지표 상세 분석
LCP
Largest Contentful Paint
가장 큰 콘텐츠가 화면에 그려지는 시간
2.5s 이하
4.0s 초과
개선 방법
- → 이미지 최적화 (WebP, lazy load)
- → 서버 응답 시간 개선
- → Critical CSS 인라인
Web Vitals 수집 코드
// 1. web-vitals 라이브러리 설치
npm install web-vitals
// 2. 측정 및 로깅
import { onLCP, onINP, onCLS, onFCP, onTTFB } from 'web-vitals';
function sendToAnalytics(metric) {
const body = JSON.stringify({
name: metric.name,
value: metric.value,
rating: metric.rating, // 'good' | 'needs-improvement' | 'poor'
delta: metric.delta,
id: metric.id,
navigationType: metric.navigationType,
});
// Beacon API로 전송 (페이지 이탈 시에도 전송 보장)
if (navigator.sendBeacon) {
navigator.sendBeacon('/analytics', body);
} else {
fetch('/analytics', { body, method: 'POST', keepalive: true });
}
}
// 모든 Core Web Vitals 측정
onLCP(sendToAnalytics);
onINP(sendToAnalytics);
onCLS(sendToAnalytics);
onFCP(sendToAnalytics);
onTTFB(sendToAnalytics);
// 3. Sentry와 연동
import * as Sentry from '@sentry/react';
import { onLCP, onINP, onCLS } from 'web-vitals';
function sendToSentry(metric) {
Sentry.setMeasurement(metric.name, metric.value, 'millisecond');
}
onLCP(sendToSentry);
onINP(sendToSentry);
onCLS(sendToSentry);측정 환경의 차이
Lab 데이터 vs Field 데이터
Lab Data (Lighthouse)는 시뮬레이션 환경이고, Field Data (RUM)는 실제 사용자 환경입니다. 두 데이터 모두 중요하지만, Field Data가 실제 사용자 경험을 반영합니다.
Lab Data (Synthetic)
- • Lighthouse / PageSpeed Insights
- • 일관된 환경에서 테스트
- • 개발 중 빠른 피드백
- • CI/CD 파이프라인 통합
Field Data (RUM)
- • CrUX Report / web-vitals
- • 실제 사용자 기기/네트워크
- • 다양한 조건 반영
- • SEO 랭킹에 사용됨
성능 대시보드 구축
Vercel Analytics
Next.js 통합, 자동 Web Vitals 수집
Sentry Performance
Web Vitals + Transaction 통합 모니터링
Google Analytics 4
Web Vitals 이벤트 자동 수집
커스텀 대시보드
Grafana + Prometheus로 자체 구축