Lesson 5 / 25
Plugins and extensions
Extend Webpack functionality with plugins.
Plugins vs loaders
Loaders transform specific file types. Plugins hook into the Webpack build lifecycle to perform broader tasks. Plugins can generate HTML files, extract CSS, minify code, analyze bundles, and more. Each plugin is instantiated and added to the plugins array.
Common plugins
Use HtmlWebpackPlugin and MiniCssExtractPlugin for production builds.
const HtmlPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
plugins: [
new HtmlPlugin({ template: './src/index.html' }),
new MiniCssExtractPlugin({ filename: '[name].[contenthash].css' })
]
};
Output:
Generates index.html and extracts CSS to separate bundle
Plugin instantiation matters
Plugins must be instantiated with 'new'. The plugins array receives plugin instances, not classes. Each plugin instance can have different configurations for different entry points or build scenarios.
Quick check
Quick check: What is the main difference between loaders and plugins?
- Loaders transform specific files; plugins hook into build lifecycle.
- Plugins process files; loaders extend lifecycle.
- They do the same thing differently.
Answer
Loaders transform specific files; plugins hook into build lifecycle. — Loaders work on individual files, while plugins hook into the Webpack compilation process to perform broader operations.