Webpack is a static module bundler for modern
JavaScript applications. It takes modules with dependencies and
generates static assets representing those modules, enabling
developers to bundle JavaScript files, CSS, images, and other assets
for use in a browser.
Core Concepts
- Entry: The starting point for building the dependency graph
- Output: Where to emit the bundled files and how to name them
- Loaders: Transform files from different languages to JavaScript
- Plugins: Perform wider range of tasks like optimization and asset management
- Mode: Development, production, or none - enables built-in optimizations
Basic Configuration
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index',
}),
],
mode: 'development',
};
Common Loaders
- babel-loader: Transpile ES6+ JavaScript to ES5
- css-loader: Resolve CSS imports and url() expressions
- style-loader: Inject CSS into the DOM
- file-loader: Handle file imports (images, fonts, etc.)
- sass-loader: Compile Sass/SCSS to CSS
- ts-loader: Compile TypeScript to JavaScript
Popular Plugins
- HtmlWebpackPlugin: Generate HTML files with bundled assets
- MiniCssExtractPlugin: Extract CSS into separate files
- CleanWebpackPlugin: Clean output directory before builds
- DefinePlugin: Define global constants at compile time
- HotModuleReplacementPlugin: Enable hot module replacement
Development vs Production
// Development mode
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
hot: true,
},
};
// Production mode
module.exports = {
mode: 'production',
optimization: {
minimize: true,
splitChunks: {
chunks: 'all',
},
},
};
Benefits
- Module System: Use ES6 modules, CommonJS, AMD
- Code Splitting: Split code into chunks for better performance
- Asset Management: Handle all types of assets (JS, CSS, images)
- Development Server: Hot reloading for faster development
- Optimization: Minification, tree shaking, and compression
- Extensibility: Rich ecosystem of loaders and plugins
Learning Path
- JavaScript Modules: Understand ES6 modules and CommonJS
- Basic Setup: Create simple webpack configuration
- Loaders: Learn to handle different file types
- Plugins: Extend functionality with plugins
- Development Setup: Configure dev server and hot reloading
- Production Optimization: Minification and code splitting
- Advanced Features: Tree shaking, lazy loading, PWA