Minify HTML Webpack Plugin

raw JSON →
1.1.7 verified Sat Apr 25 auth: no javascript

A webpack plugin that minifies HTML files using html-minifier after the webpack build. Version 1.1.7 supports webpack 2-5 and Node >= 6.0. It iterates through source directories recursively, copying and minifying all HTML files. Key features include search-and-replace before minification and an afterBuild option to run after webpack completes. The plugin is mainly used in PHP/Laravel projects to minify Blade-compiled views. Released sporadically, last update in 2021.

error Error: Cannot find module 'html-minifier'
cause Missing dependency; html-minifier is not automatically installed.
fix
Run 'npm install html-minifier --save-dev'
error TypeError: Cannot read property 'replace' of undefined
cause searchAndReplace array entry missing 'search' or 'replace' property.
fix
Ensure each object in searchAndReplace has both 'search' and 'replace' fields.
error MinifyHtmlWebpackPlugin is not a constructor
cause Using default import instead of require in CommonJS.
fix
Use 'const MinifyHtmlWebpackPlugin = require('minify-html-webpack-plugin');'
error The 'src' directory does not exist
cause Provided src path is invalid or does not exist.
fix
Ensure src directory exists and path is correct.
gotcha Plugin does not work with Webpack Dev Server; it only runs on production builds.
fix Only use in production webpack config, not in development.
breaking The `afterBuild` option was added in v1.1.4; prior versions always ran after build but now it defaults to false.
fix Set `afterBuild: true` if you require post-build processing.
deprecated The `searchAndReplace` option uses `search` and `replace` fields; `search` can be a string or regex.
fix No action needed unless you rely on the undocumented array of strings feature.
gotcha Plugin copies only files from `src` to `dest`; existing files in `dest` not overwritten unless matching source.
fix Ensure `dest` is empty or has matching file structure.
gotcha Html-minifier rules are passed directly; invalid rules may cause errors or be ignored silently.
fix Refer to html-minifier documentation for valid rules.
npm install minify-html-webpack-plugin
yarn add minify-html-webpack-plugin
pnpm add minify-html-webpack-plugin

Basic config to minify HTML files from src/html to dist/html after webpack build.

// webpack.config.js
const path = require('path');
const MinifyHtmlWebpackPlugin = require('minify-html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new MinifyHtmlWebpackPlugin({
      src: path.resolve(__dirname, 'src/html'),
      dest: path.resolve(__dirname, 'dist/html'),
      rules: {
        collapseBooleanAttributes: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true,
        removeComments: true,
        minifyJS: true,
        minifyCSS: true
      }
    })
  ]
};