Webpack은 JavaScript 모듈 번들러로, 애플리케이션의 모든 의존성을 분석해 하나 이상의 번들 파일로 결합한다. 코드 분할, 트리 쉐이킹, 핫 모듈 교체(HMR) 등 현대 웹 개발의 필수 기능을 제공한다.
핵심 개념
Entry → Module Graph → Chunks → Output
webpack은:
1. Entry 파일(index.js)에서 시작
2. import/require 따라 의존성 그래프 구성
3. Loaders로 각 모듈 변환 (.css, .ts, 이미지 등)
4. Plugins로 번들 최적화
5. 최종 Output 파일 생성
기본 설정
javascript
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
clean: true,
},
module: {
rules: [
{ test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
{ test: /\.(png|svg|jpg)$/, type: 'asset/resource' },
],
},
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })],
optimization: {
splitChunks: { chunks: 'all' }, // 코드 분할
},
};
트리 쉐이킹
javascript
// math.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b; // 사용 안 함
// index.js
import { add } from './math'; // multiply는 번들에서 제거됨
Webpack vs Vite 비교
| Webpack | Vite |
|---|
| 개발 서버 | 번들 후 서빙 | ESM 네이티브 (번들 없음) |
| HMR 속도 | 느림 (전체 재번들) | 빠름 (변경 모듈만) |
| 설정 복잡도 | 높음 | 낮음 |
| 생태계 | 매우 성숙 | 빠르게 성장 |
| 프로덕션 빌드 | 자체 | Rollup 사용 |
관련 개념