Comprehensive Guide to HTML Minifier Optimizing Your Web Performance with API Examples

Introduction to HTML Minifier

HTML Minifier is a highly efficient plugin designed to minimize HTML code, enhancing web performance and ensuring faster load times. This comprehensive guide will walk you through dozens of useful API examples to showcase the power and flexibility of HTML Minifier.

Getting Started

To get started with HTML Minifier, you need to install it through npm:

npm install html-minifier

Basic Usage


const minify = require('html-minifier').minify;
const html = 'Title

Hello, world!

'; const minified = minify(html, { removeComments: true, collapseWhitespace: true, minifyCSS: true, minifyJS: true, removeEmptyAttributes: true }); console.log(minified);

API Examples

Collapse Boolean Attributes


const result = minify('', {
  collapseBooleanAttributes: true
});
// Output: 

Remove Attribute Quotes


const result = minify('

baz

', { removeAttributeQuotes: true }); // Output:

baz

Collapse Whitespace


const result = minify('

foo

', { collapseWhitespace: true }); // Output:

foo

Remove Comments


const result = minify(' 

foo

', { removeComments: true }); // Output:

foo

App Example

Here’s a simple example that demonstrates how to integrate HTML Minifier into a Node.js application:


const express = require('express');
const fs = require('fs');
const minify = require('html-minifier').minify;

const app = express();

app.get('/', (req, res) => {
  const html = fs.readFileSync('index.html', 'utf8');
  const minifiedHtml = minify(html, {
    removeComments: true,
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true
  });
  res.send(minifiedHtml);
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

This example reads an HTML file, minifies it using HTML Minifier, and serves the optimized HTML content via an Express server.

Hash: a2c49194fa8216e48ebf31c55c7b7cdfecdf9712fef3c2885137f27f343e0542

Leave a Reply

Your email address will not be published. Required fields are marked *