Webpack Basics
Webpack - What is it and how does it work?
Webpack is a JavaScript module bundler that allows developers to efficiently manage their project dependencies. It combines various files (JavaScript, CSS, images, etc.) into a single unified bundle, improving performance speed and browser loading efficiency.
Webpack operates through the following core components:
Entry Point
The Entry Point is the main file that Webpack takes as a starting point to load all dependencies. For example:
module.exports = { entry: './src/index.js' };
Output
Output – the file where the final bundle is stored. For example:
output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }
Loaders
Loaders – help process non-JavaScript files (CSS, images, fonts, etc.). For example:
module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.png$/, use: ['file-loader'] } ] }
Plugins
Plugins – add additional functionalities, such as HtmlWebpackPlugin, which automatically generates an HTML file. For example:
const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })] };
Mode
Mode – allows selecting either development or production mode. For example:
mode: 'production'
The main configuration of Webpack is defined in the webpack.config.js file. Here is an example:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, mode: 'development', module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.png$/, use: ['file-loader'] } ] }, plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })] };
Code Splitting
Code Splitting – allows splitting the code into multiple bundles, reducing the size of the main file. For example:
module.exports = { optimization: { splitChunks: { chunks: 'all', }, }, };
Tree Shaking
Tree Shaking – removes unused code, improving the program's performance.
Caching
Caching – uses hashed files to prevent the browser from loading the same file multiple times.
Minification
Minification – reduces and optimizes JavaScript code using TerserPlugin or Webpack's built-in capabilities.
const TerserPlugin = require('terser-webpack-plugin'); module.exports = { optimization: { minimize: true, minimizer: [new TerserPlugin()], }, };
Feature | Webpack | Vite | Parcel | ESBuild |
Module Bundling | ✅ | ✅ | ✅ | ✅ |
Speed | Medium | Very Fast | Fast | Very Fast |
Configuration | Required | Practically Not Needed | Easy | Easy |
Optimization | ✅ | ✅ | ✅ | ✅ |