Webpack Optimized Performance
const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
module.exports = {
mode: "production", // Ensures Webpack runs in optimized mode
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "js/[name].[contenthash].js", // Cache-busting
chunkFilename: "js/[name].[contenthash].chunk.js", // Cache-busting for chunks
publicPath: "/", // Set according to deployment needs
},
module: {
rules: [
// JavaScript / JSX
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
// CSS / SCSS
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader"],
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
// Image Optimization
{
test: /\.(png|jpg|jpeg|gif|svg)$/,
type: "asset",
parser: {
dataUrlCondition: {
maxSize: 8 * 1024, // Inline images below 8KB
},
},
},
],
},
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
parallel: true, // Use multi-threading
extractComments: false, // Remove comments
terserOptions: {
compress: {
drop_console: true, // Remove console.logs
},
},
}),
new CssMinimizerPlugin(), // Minify CSS
],
// 🚀 **Code Splitting for Better Performance**
splitChunks: {
chunks: "all",
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
chunks: "all",
},
},
},
// ✅ Persistent caching for faster rebuilds
runtimeChunk: "single",
},
plugins: [
new CleanWebpackPlugin(), // Cleans old builds
new MiniCssExtractPlugin({
filename: "css/[name].[contenthash].css",
}),
new CompressionPlugin({
algorithm: "gzip", // Compress assets with Gzip
test: /\.(js|css|html|svg)$/,
threshold: 10240, // Only compress assets > 10KB
minRatio: 0.8,
}),
new BundleAnalyzerPlugin({
analyzerMode: "static",
openAnalyzer: false,
}),
],
performance: {
hints: "warning",
maxEntrypointSize: 400000, // Warn if entry file exceeds 400KB
maxAssetSize: 250000, // Warn if asset exceeds 250KB
},
devtool: "source-map", // Helps in debugging, remove for production
};
Key Optimizations Explained
Webpack optimization is crucial for improving performance, reducing bundle size, and enhancing load speed. This guide covers essential optimization techniques.
1️⃣ Production Mode
What it does
Enables built-in optimizations like minification, tree shaking, and better performance settings.
Webpack has two modes:
development
- For debugging, with detailed source maps.production
- Optimized output with minification.
✅ Enable Production Mode
module.exports = {
mode: 'production', // Enables built-in optimizations
};
Or via CLI:
webpack --mode=production
2️⃣ Code Splitting (Split Your Bundle)
What it does
Breaks down large JavaScript files into smaller chunks, improving loading speed and caching efficiency.
✅ Example: Split Vendor & App Code
module.exports = {
optimization: {
splitChunks: {
chunks: 'all', // Splits both vendor and app code
},
},
};
➡️ This generates vendor.js
(third-party libraries) and main.js
(app code), making caching more efficient.
3️⃣ Tree Shaking (Remove Unused Code)
What it does
Removes dead or unused code from the final bundle to reduce file size and improve performance.
Tree shaking removes unused exports from your final bundle. Works best with ES6 Modules (import/export
).
✅ Enable Tree Shaking
module.exports = {
mode: 'production',
optimization: {
usedExports: true, // Mark unused exports for removal
},
};
4️⃣ Minify JavaScript & CSS
What it does
Minification removes unnecessary characters (whitespace, comments) to reduce file sizes and speed up page loads.
✅ JavaScript Minification (TerserPlugin)
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
};
✅ CSS Minification
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
module.exports = {
optimization: {
minimizer: [new CssMinimizerPlugin()],
},
};
5️⃣ Enable Gzip/Brotli Compression
What it does
Compresses static assets to reduce their transfer size, leading to faster load times.
✅ Use compression-webpack-plugin
npm install compression-webpack-plugin
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
plugins: [
new CompressionPlugin({
algorithm: "gzip",
test: /\.(js|css|html)$/, // Compress JS, CSS, HTML
}),
],
};
6️⃣ Lazy Loading (Load Only When Needed)
What it does
Improves performance by loading JavaScript files only when required, rather than at initial load.
const Component = React.lazy(() => import('./Component'));
7️⃣ Optimize Images
What it does
Compresses images to reduce their size, improving page speed and load performance.
✅ Use image-webpack-loader
to Compress Images
npm install image-webpack-loader
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: [
{
loader: 'image-webpack-loader',
options: {
mozjpeg: { progressive: true },
optipng: { optimizationLevel: 5 },
},
},
],
},
],
},
};
8️⃣ Cache Busting (Long-Term Caching)
What it does
Ensures users always receive the latest version of files by appending unique hashes to filenames.
✅ Use [contenthash]
in Filenames
module.exports = {
output: {
filename: '[name].[contenthash].js',
},
};
9️⃣ Optimize Webpack Build Speed
What it does
Reduces build times by caching dependencies and running loaders in parallel.
✅ Enable Hard Source Caching
npm install hard-source-webpack-plugin
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
plugins: [
new HardSourceWebpackPlugin(),
],
};
10. Performance Hints
- Warns if bundles exceed optimal sizes.
11. Persistent Caching**
- Webpack caches modules efficiently, reducing build times.
✅ Speed Up Rebuilds with Thread Loader
npm install thread-loader
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: 'thread-loader', // Runs loaders in a separate thread
},
],
},
};
🎯 Summary
✅ Production Mode for optimizations.
✅ Code Splitting for better caching.
✅ Tree Shaking to remove unused code.
✅ Minify JavaScript & CSS for smaller bundles.
✅ Enable Compression (Gzip/Brotli).
✅ Lazy Load Components for performance.
✅ Optimize Images for faster loading.
✅ Cache Busting for long-term caching.
✅ Speed Up Builds with caching & multi-threading.