Tags: webpack, build, bundler, javascript, frontend, assets
Level: intermediate
TL;DR: Webpack is a static module bundler for modern JavaScript applications that builds a dependency graph of your project and generates optimized bundles for production.
-
Entry: The entry point indicates which module Webpack should use to begin building out its internal dependency graph.
-
Output: Tells Webpack exactly where to emit the bundles it creates and how to name these files.
-
Loaders: Enable Webpack to process non-JavaScript files (like CSS, TS, SVG) and convert them into valid modules.
-
Plugins: Handle wider tasks such as bundle optimization, asset management, and environment variable injection.
-
Mode: Setting mode to development or production enables Webpack's built-in optimizations for those specific environments.
-
Dependency Graph: Webpack recursively builds this graph by analyzing import and require statements across the codebase.
-
Hot Module Replacement (HMR): Updates modules in the browser at runtime without requiring a full page refresh during development.
-
Code Splitting: The process of splitting code into various bundles which can then be loaded on demand or in parallel.
-
Q: What is the difference between a loader and a plugin?R: Loaders work at the individual file level during the build to transform code. Plugins work at the bundle level to modify the overall build process.
-
Q: How does tree shaking work in Webpack?R: Tree shaking relies on static analysis of ES6 modules (import/export). In production mode, Webpack drops unused exports to shrink the final bundle.
-
Forgetting to explicitly set mode: 'production', which leads to deploying massive, unminified, and unoptimized bundles.
-
Misunderstanding loader evaluation order. Loaders are executed from right-to-left (or bottom-to-top) in the configuration array.
-
Overusing plugins or overly complex configurations, which significantly slows down the build performance.
```const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
clean: true,
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
mode: 'production',
};
npm init -y
npm install webpack webpack-cli --save-dev
npx webpack --config webpack.config.js
```
-
[ ] SplitChunksPlugin configuration for effective caching.
-
[ ] Module Federation basics for micro-frontend architectures.
-
Webpack Official Documentation (webpack.js.org)