Webpack 최적화 완벽 가이드 | 번들 크기·빌드 속도·Code Splitting·Tree Shaking

Webpack 최적화 완벽 가이드 | 번들 크기·빌드 속도·Code Splitting·Tree Shaking

이 글의 핵심

Webpack 빌드를 최적화하는 완벽 가이드입니다. 번들 크기 줄이기, 빌드 속도 향상, Code Splitting, Tree Shaking, 캐싱까지 실전 예제로 정리했습니다.

실무 경험 공유: 레거시 Webpack 설정을 최적화하면서, 번들 크기를 5MB에서 500KB로 줄이고 빌드 시간을 10분에서 2분으로 단축한 경험을 공유합니다.

들어가며: “Webpack이 너무 느려요”

실무 문제 시나리오

시나리오 1: 번들이 5MB예요
초기 로딩이 10초 걸립니다. 최적화로 500KB, 2초로 단축합니다.

시나리오 2: 빌드가 10분 걸려요
CI/CD가 느립니다. 캐싱과 병렬 처리로 2분으로 단축합니다.

시나리오 3: 모든 코드가 하나의 파일이에요
첫 페이지만 보는데 전체를 다운로드합니다. Code Splitting으로 해결합니다.


1. Webpack이란?

핵심 특징

Webpack은 모듈 번들러입니다.

주요 기능:

  • 번들링: 여러 파일을 하나로
  • Code Splitting: 필요한 것만 로드
  • Tree Shaking: 사용 안 하는 코드 제거
  • 로더: CSS, 이미지 등 처리
  • 플러그인: 확장 기능

2. 번들 크기 줄이기

Tree Shaking

// webpack.config.js
module.exports = {
  mode: 'production',  // Tree Shaking 활성화
  optimization: {
    usedExports: true,
  },
};
// package.json
{
  "sideEffects": false  // 모든 파일이 side-effect 없음
}

// 또는 특정 파일만
{
  "sideEffects": ["*.css", "*.scss"]
}

Minification

const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true,  // console.log 제거
          },
        },
      }),
    ],
  },
};

번들 분석

npm install -D webpack-bundle-analyzer
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin(),
  ],
};

3. Code Splitting

Dynamic Import

// 동적 import
button.addEventListener('click', async () => {
  const module = await import('./heavy-module');
  module.doSomething();
});

React Lazy

import { lazy, Suspense } from 'react';

const Dashboard = lazy(() => import('./Dashboard'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Dashboard />
    </Suspense>
  );
}

SplitChunks

module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          priority: 10,
        },
        common: {
          minChunks: 2,
          priority: 5,
          reuseExistingChunk: true,
        },
      },
    },
  },
};

4. 빌드 속도 향상

캐싱

module.exports = {
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename],
    },
  },
};

thread-loader (병렬 처리)

npm install -D thread-loader
module.exports = {
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          'thread-loader',
          'ts-loader',
        ],
      },
    ],
  },
};

불필요한 플러그인 제거

// ❌ 개발에서 불필요
new MiniCssExtractPlugin()  // CSS 추출

// ✅ 프로덕션에만
if (isProduction) {
  plugins.push(new MiniCssExtractPlugin());
}

5. 이미지 최적화

npm install -D image-webpack-loader
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                progressive: true,
                quality: 65,
              },
              optipng: {
                enabled: false,
              },
              pngquant: {
                quality: [0.65, 0.90],
                speed: 4,
              },
            },
          },
        ],
      },
    ],
  },
};

6. 캐싱 전략

Content Hash

module.exports = {
  output: {
    filename: '[name].[contenthash].js',
    chunkFilename: '[name].[contenthash].chunk.js',
  },
};

Runtime Chunk

module.exports = {
  optimization: {
    runtimeChunk: 'single',  // 런타임 코드 분리
  },
};

7. 실전 예제: 최적화된 설정

// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
  mode: 'production',
  entry: './src/index.tsx',
  
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js',
    chunkFilename: '[name].[contenthash].chunk.js',
    clean: true,
  },

  cache: {
    type: 'filesystem',
  },

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: ['thread-loader', 'ts-loader'],
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'],
      },
    ],
  },

  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true,
          },
        },
      }),
      new CssMinimizerPlugin(),
    ],
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          priority: 10,
        },
      },
    },
    runtimeChunk: 'single',
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
    }),
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css',
    }),
  ],

  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
};

정리 및 체크리스트

핵심 요약

  • Tree Shaking: 사용 안 하는 코드 제거
  • Code Splitting: 필요한 것만 로드
  • Minification: 코드 압축
  • 캐싱: 빌드 속도 향상
  • 병렬 처리: thread-loader
  • 번들 분석: webpack-bundle-analyzer

최적화 체크리스트

  • Tree Shaking 활성화
  • Code Splitting 구현
  • Minification 설정
  • 캐싱 활성화
  • 이미지 최적화
  • 번들 분석
  • Content Hash 적용

같이 보면 좋은 글

  • Vite 5 완벽 가이드
  • Turborepo 완벽 가이드
  • React 18 심화 가이드

이 글에서 다루는 키워드

Webpack, Build Tool, Optimization, Performance, Bundle, Frontend

자주 묻는 질문 (FAQ)

Q. Webpack vs Vite, 어떤 게 나은가요?

A. Vite가 훨씬 빠릅니다. 새 프로젝트는 Vite를 권장합니다. 레거시 프로젝트는 Webpack 최적화를 고려하세요.

Q. 번들 크기 목표는?

A. 초기 번들은 200KB 이하를 권장합니다. 전체 앱은 1MB 이하가 이상적입니다.

Q. Tree Shaking이 안 되는 이유는?

A. sideEffects 설정을 확인하세요. 또는 라이브러리가 ESM을 지원하지 않을 수 있습니다.

Q. 빌드 시간을 더 줄일 수 있나요?

A. 캐싱, thread-loader, 불필요한 플러그인 제거를 시도하세요. 또는 Vite로 마이그레이션을 고려하세요.

... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3