Lesson 5 / 25

Plugins and extensions

Extend Webpack with plugins such as HtmlWebpackPlugin and MiniCssExtractPlugin, and see how they differ from loaders.

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?

  • Plugins process files; loaders extend lifecycle.
  • Loaders transform specific files; plugins hook into build lifecycle.
  • They do the same thing differently.
  • Plugins only run after the build finishes.
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.