htmlnano

repository·master·Indexed 43 days ago

https://github.com/maltsev/htmlnano

A modular HTML minifier built on top of PostHTML, inspired by cssnano. It provides a highly configurable way to optimize production HTML via a JavaScript API or CLI, featuring built-in presets like safe, ampSafe, and max. It supports integration with Webpack via html-minimizer-webpack-plugin and Gulp via gulp-posthtml.

Tokens
18.8K
Snippets
65
Records
71
Agent score
54%

What's inside htmlnano

  1. Configure htmlnano modules

    master

    By default, htmlnano only performs safe transformations. You can customize which modules are active by passing an options object where the keys are the module names.

    • To disable a specific module, pass false as its value.
    • To enable a specific module, pass true as its value.

    Important: The order in which you define modules in your configuration determines the order in which they are applied to your HTML. The modules are applied in the sequence they appear in the configuration object.

  2. How htmlnano works

    master

    htmlnano processes HTML using an ordered set of modules, where each module handles a specific concern such as comments, whitespace, attributes, inline CSS, or inline JS. This modularity makes behavior predictable and easy to tune.

    To use htmlnano effectively, follow this typical workflow:

    1. Select a preset: Start with a baseline like safe, ampSafe, or max.
    2. Customize: Override only the specific modules you need to adjust.
    3. Execute: Run htmlnano as the final step in your PostHTML pipeline.
  3. Use a preset with htmlnano.process()

    master

    You can apply a preset by passing it as the third argument to htmlnano.process(). You can either access presets via the main htmlnano object or import them directly from their specific paths.

    Using CommonJS:

    const htmlnano = require('htmlnano');
    const ampSafePreset = require('htmlnano').presets.ampSafe;
    
    htmlnano.process(html, { collapseWhitespace: 'conservative' }, ampSafePreset)
        .then((result) => {
            // result.html is minified
        })
        .catch((err) => {
            console.error(err);
        });

    Using ESM:

    import htmlnano from 'htmlnano';
    import ampSafe from 'htmlnano/presets/ampSafe';
    
    const result = await htmlnano.process(html, {}, ampSafe);
    const ampSafePreset = require('htmlnano').presets.ampSafe;
    htmlnano.process(html, { collapseWhitespace: 'conservative' }, ampSafePreset)
  4. Disable configuration auto-discovery

    master

    By default, htmlnano walks up from process.cwd() to find a configuration file. This can be a security risk if running in untrusted directories, as executable config files (like .htmlnanorc.js) are require()d and run with your privileges.

    To disable this implicit lookup:

    • In the library: Set skipConfigLoading: true in the options object.
    • In the CLI: Use the --no-config-search flag.

    Note: Using --no-config-search in the CLI does not prevent you from loading a specific trusted file using -c or --config <file>.

    # CLI
    npx htmlnano test.html --no-config-search
  5. Run htmlnano-docs in local development mode

    master

    Start a local development server to view the website. This command will automatically open a browser window and support live reloading, so most changes are reflected immediately without a server restart.

    npm start
  6. Create a custom preset by extending a built-in one

    master

    You can create your own presets by spreading an existing built-in preset into a new object and overriding or adding specific module configurations.

    const htmlnano = require('htmlnano');
    const emailPreset = {
        ...htmlnano.presets.safe,
        mergeStyles: true,
        minifyCss: {
            safe: true
        }
    };
    
    htmlnano.process(html, { removeComments: false }, emailPreset)
        .then((result) => {
            // result.html is minified
        })
        .catch((err) => {
            console.error(err);
        });
  7. Define a custom configuration without presets

    master

    To define your own configuration from scratch without inheriting any preset settings, pass an empty object {} as the third argument to htmlnano.process().

    const htmlnano = require('htmlnano');
    const options = {
        // Your options
    };
    
    htmlnano
        .process(html, options, {})
        .then(function (result) {
            // result.html is minified
        })
        .catch(function (err) {
            console.error(err);
        });
  8. Integrate htmlnano with Webpack

    master

    To use htmlnano in Webpack, use the html-minimizer-webpack-plugin. You must provide htmlnano.htmlMinimizerWebpackPluginMinify as the minify option.

    npm install html-minimizer-webpack-plugin --save-dev
    // webpack.config.js
    const HtmlMinimizerWebpackPlugin = require('html-minimizer-webpack-plugin');
    const htmlnano = require('htmlnano');
    
    module.exports = {
        optimization: {
            minimize: true,
            minimizer: [
                    // For webpack@5, use '...' to extend existing minimizers
                    '...',
                    new HtmlMinimizerWebpackPlugin({
                        // Add HtmlMinimizerWebpackPlugin options here.
                        // test: /\.html(\?.*)?$/i,
    
                        // Use htmlnano as HtmlMinimizerWebpackPlugin's minimizer.
                        minify: htmlnano.htmlMinimizerWebpackPluginMinify,
                        minimizerOptions: {
                            // Add htmlnano options here.
                            removeComments: false,
                            collapseWhitespace: 'conservative'
                        }
                    })
                ]
        }
    }