Giter Club home page Giter Club logo

minify-html-webpack-plugin's Introduction

Webpack plugin: minify-html-webpack-plugin

npm node-current npm Libraries.io dependency status for GitHub repo NPM

This is a webpack plugin that can minimize the HTML with HTMLMinifier for all source directory files and copy into destinations directory recursively iterating through all subfolders and files during the Webpack build.

Installation

Install the plugin with npm:

$ npm install minify-html-webpack-plugin --save-dev

Heads up!

Please do not report issues related to HTML parsing and output on this repository. Report those issues to the html-minifier issue tracker.

Basic Usage

Add the plugin to your webpack and config as follows:

    const MinifyHtmlWebpackPlugin = require('minify-html-webpack-plugin');
    const webpackConfig = {
        plugins: [
            new MinifyHtmlWebpackPlugin({
                src: './storage/framework/views',
                dest: './storage/framework/views',
                rules: {
                    collapseBooleanAttributes: true,
                    collapseWhitespace: true,
                    removeAttributeQuotes: true,
                    removeComments: true,
                    minifyJS: true,
                }
            });
        ]
    };

Optional Add Search And Replace Rules

If need to replace strings and then do minification across all source files in directoris and sub-directories.

    const MinifyHtmlWebpackPlugin = require('minify-html-webpack-plugin');
    const webpackConfig = {
        plugins: [
            new MinifyHtmlWebpackPlugin({
                src: './storage/framework/views',
                dest: './storage/framework/views',
                rules: {
                    collapseBooleanAttributes: true,
                    collapseWhitespace: true,
                    removeAttributeQuotes: true,
                    removeComments: true,
                    minifyJS: true,
                },
                searchAndReplace: [
                    {
                        /* The string, or regular expression, that will be replaced by the new value */
                        search: 'search_string',
                        /* The string to replace the search value with */
                        replace: 'replace_string' 
                    }
                ]
            });
        ]
    };

If need to replace array of string with common replace funtions and then minify it across source files and sub-directories.

    const MinifyHtmlWebpackPlugin = require('minify-html-webpack-plugin');
    const webpackConfig = {
        plugins: [
            new MinifyHtmlWebpackPlugin({
                afterBuild: true,
                src: './storage/framework/views',
                dest: './storage/framework/views',
                rules: {
                    collapseBooleanAttributes: true,
                    collapseWhitespace: true,
                    removeAttributeQuotes: true,
                    removeComments: true,
                    minifyJS: true,
                },
                searchAndReplace: [
                   {
                        search: './domain',
                        replace: 'https://original.domain.com'
                    },
                    {
                        /* The array of string value, or regular expression, that will be replaced by the new value returened from replace function */
                        search: ['./css/app.css', './js/app.js'],
                        replace: (searchString, index) => {
                            /* The custom replace logic to replace the search value with */

                            /* Example: Logic to to replace css, js file names with full domain name as prefix and version as suffix to it.

                                    './css/app.css' => 'https://original.domain.com/css/app.css?id=91352d1f26a97b89f271'
                                    './js/app.js' => 'https://original.domain.com/js/app.js?id=a1f1ae0cfce9bc2d3ce6'

                            */
                            const content = fs.readFileSync(path.resolve('/real/path/of/file', searchString), 'utf8');
                            return 'https://original.domain.com' + searchString.substring(1) + '?id=' + md5(content).substr(0, 20);
                        }
                    },
                ]
            });
        ]
    };

Laravel Mix Users

Paste below snippets into webpack.mix.js file.

    const MinifyHtmlWebpackPlugin = require('minify-html-webpack-plugin');
    const mix = require('laravel-mix');

    mix.webpackConfig({
        plugins: [
            new MinifyHtmlWebpackPlugin({
                afterBuild: true,
                src: './storage/framework/views',
                dest: './storage/framework/views',
                ignoreFileNameRegex: /\.(gitignore|php)$/,
                ignoreFileContentsRegex: /(<\?xml version)|(mail::message)/,
                rules: {
                    collapseBooleanAttributes: true,
                    collapseWhitespace: true,
                    removeAttributeQuotes: true,
                    removeComments: true,
                    minifyJS: true,
                }
            })
        ]
    });

Configuration

You can pass configuration options to MinifyHtmlWebpackPlugin. Each configuration has following items:

  • afterBuild: Optional. Add afterBuild:true, if you want to run complete minification process after webpack build, at the end.
  • dir: Optional. Base dir to find the files, if not provided, use the root of webpack context.
  • src: Required. source directory path.
  • dest: Required. destination directory path. Paste minified HTML contents from src directory files into dest directory.
  • ignoreFileNameRegex: Optional. Regex Expression to ingnore files in the src directory if it matches with the file name, if not provided, will minimize all files in src directory.`
  • ignoreFileContentsRegex: Optional. Regex Expression to ingnore files in the src directory if it matches with the file contents, if not provided, will minimize all files in src directory.`
  • rules: Required. See the html-minifer docs for all available options.
  • searchAndReplace: Optional. Array of all search and replace rules. check above examples.

License

This project is licensed under MIT.

minify-html-webpack-plugin's People

Contributors

ashutoshsce avatar colinwirt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

minify-html-webpack-plugin's Issues

Call plugin at the end of build

Is there a way to call this plugin at the end of build?
I'm using laravel-mix with laravel-mix-nunjucks plugin to compile nunjucks files into html, so the files don't exist yet. Maybe it's not even this plugin-related question.

Script minifies the original source code. No warning!

After running the script, I found that it performs minification on the original source HTML file itself by default. Usually this behaviour is not expected and can cause damage in case the source file is not protected using a version control.

Potential Fixes (in the descending order of preference):

  1. Read the webpack's output>path directory and pass it to the script.
  2. Throw an error when dest is not provided in the options.
  3. Make it explicit in the README that dest is needed and provide a warning that original source code will be overwritten if dest is missing from the options.

`path` is not defined

When running the wepack command to perform a build, it throws an error:

ReferenceError: path is not defined
    at C:\Users\Rishab Manocha\Source code\agency-website\node_modules\minify-html-webpack-plugin\index.js:24:28

Looking in the index.js file, it looks like the you forgot to add

const path = require('path');

Search and Replace

Is it possible to search and replace a string in all .HTML files? For example, I have a string "CACHE_KEY" that I want to find every instance of in all HTML files and have it replaced with a hash. It seems to search and replace will find the first instance, then stop. I was hoping it can search the entire dist direct and replace all.

The script fails if the `src` directory contains any directory

If the source directory contains a folder inside apart from the expected html files, the script results in an error since it is expecting to read a file.

Potential Fixes:

  1. Check before reading whether a file is a directory or not.
  2. Create enhancement to recursively go through all the subdirectories and look up for HTML files.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.