terser 와 tree shaking
요약
Tree-shaking과 Terser 정리
Tree-shaking
"사용하지 않는 코드를 흔들어서 떨어뜨린다"는 의미입니다.
작동 방식
// math.js 파일
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }
export function multiply(a, b) { return a * b; }
// main.js 파일
import { add } from './math.js'; // subtract, multiply는 사용 안 함
console.log(add(1, 2));Tree-shaking 전: 모든 함수 포함 (add, subtract, multiply)
Tree-shaking 후: 사용하는 함수만 포함 (add만)
장점
번들 크기 감소
로딩 속도 향상
메모리 사용량 감소
Terser
JavaScript 코드를 압축하고 최적화하는 도구입니다.
작동 방식
// 원본 코드
function calculateTotal(price, tax) {
const taxAmount = price * tax;
const total = price + taxAmount;
console.log("Total calculated:", total);
return total;
}
// Terser 압축 후
function calculateTotal(e,t){const a=e*t;return e+a}최적화 기능
변수명 단축: price → e, tax → t
불필요한 공백 제거: 한 줄로 압축
console.log 제거: drop_console: true 설정 시
Dead Code 제거: 사용하지 않는 코드 삭제
코드 압축: 의미는 같지만 더 짧은 코드로 변환
프로젝트에서의 효과
Vite 설정에서
terserOptions: {
compress: {
drop_console: true, // console.log 제거
drop_debugger: true, // debugger 제거
dead_code: true, // 사용 안 하는 코드 제거
unused: true, // 사용 안 하는 변수 제거
},
mangle: true, // 변수명 단축
}실제 효과
501KB → 463KB: 약 38KB (7.7%) 감소
로딩 속도: 더 빠른 다운로드
파싱 속도: 더 적은 코드 처리
