Optimize webpack builds and performance
🎯 Introduction
This article introduces webpack optimization techniques that help your frontend project build faster, produce smaller bundles, and load resources more efficiently. Code splitting, lazy loading, unused code removal, and caching all contribute to a better user experience and a more efficient development workflow.
🧩 Code splitting
Code splitting is one of webpack's most useful performance optimization techniques. It splits code into chunks that browsers can load on demand, reducing the work required for the initial page load.
Consider an online store. Loading all product details and feature code at once would slow down the first visit. With code splitting, the home page loads only what it needs, and product detail code loads when the user selects a product, creating a smoother experience.
webpack supports three main approaches to code splitting:
- Entry points: configure multiple entries to generate a separate bundle for each one.
- Prevent duplication (use SplitChunksPlugin; CommonsChunkPlugin is deprecated): extract dependencies shared by multiple entries.
- Dynamic imports: load modules dynamically with
import(), introduced through the ECMAScript proposal process, for flexible code splitting.
Example:
// Dynamic import example
function loadComponent() {
import('./MyComponent').then(({ default: MyComponent }) => {
// Use the loaded component
MyComponent.render();
});
}
This tells webpack to place MyComponent in a separate chunk and load it only when this code executes.
🕹️ Lazy loading and loading on demand
Lazy loading builds on code splitting by loading code or resources only when needed, avoiding the delays caused by loading everything up front.
Loading on demand often integrates with routing. For example, Vue Router can lazy-load route components:
// Route configuration with lazy loading
const routes = [
{
path: '/',
component: () => import('./components/Home.vue'), // Lazy-load this component
},
{
path: '/about',
component: () => import('./components/About.vue'), // Lazy-load this component
},
];
const router = new VueRouter({
mode: 'history',
routes,
});
The component code loads only when the user visits its route.
Lazy loading also applies to images, data, and other resources:
<img loading="lazy" src="big-photo.jpg" alt="Large photo" />
Modern browsers support loading="lazy", which defers image loading to save bandwidth.
🌳 Tree shaking (removing unused code)
Tree shaking uses the static structure of ES modules to remove unused code and reduce bundle size.
Think of grocery shopping: you buy only the ingredients you need, rather than everything in the store. Tree shaking similarly leaves out code you do not use.
To enable tree shaking, make sure that:
- You use ES module
importandexportsyntax. CommonJSrequiredoes not provide the same static structure for tree shaking. - You build in production mode (
mode: 'production'), which enables the relevant optimizations by default. - You set
"sideEffects": falsein package.json when your modules have no side effects, allowing webpack to safely omit unused modules.
Example:
export function useful() {
console.log('Useful function');
}
export function unused() {
console.log('Unused function');
}
import { useful } from './utils';
useful();
The build removes the unused unused function.
package.json to avoid removing necessary behavior. For example, "sideEffects": ["*.css"] preserves CSS side effects.💾 Optimize caching with content hashes
Caching is an important part of build optimization. Effective caching prevents users from downloading unchanged assets repeatedly and improves loading efficiency.
webpack's contenthash placeholder includes a hash of the file contents in its filename. When the content changes, the filename changes, prompting the browser to request the new file.
Example configuration:
module.exports = {
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
},
};
The generated filenames look like this:
main.1a2b3c4d.js
vendor.5d6e7f8g.js
When you change code, its hash changes and the browser downloads the updated file. Unchanged files can continue to load from cache.
Combine this with code splitting for more granular caching:
- Extract third-party libraries into separate chunks
- Extract shared code into shared chunks
Example configuration:
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
},
runtimeChunk: {
name: 'runtime',
},
},
};
This allows vendor, runtime, and application code to be cached independently.
❓ Questions and answers
Q1: How do code splitting and lazy loading differ?
Code splitting divides code into chunks. Lazy loading loads those chunks on demand and is one way to use code splitting.
Q2: Does tree shaking work with every module format?
The approach described here relies on ES module import and export syntax. CommonJS modules do not provide the same static structure for tree shaking.
🧪 Exercises
Exercise 1
Configure webpack to use contenthash in output filenames and extract shared code with SplitChunksPlugin.
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
// TODO: Configure contenthash here
},
optimization: {
// TODO: Enable code splitting
},
};
🎉 You can now use webpack's code splitting, lazy loading, tree shaking, and caching techniques! Try these essential tools for building high-performance frontend applications in your own project.
HMR and development mode
Compare development and production modes, configure hot module replacement with webpack-dev-server, and debug efficiently with source maps.
Build for production with webpack
Learn production build techniques, including minification, CSS extraction, environment variables, separate environment configurations, and bundle analysis.
