html-minifier

html-minifier embeds the widely-used html-minifier NPM package in an easy-to-use Crystal shard via duktape.cr, which provides a fast, embedded Javascript execution environment within Crystal.

html-minifier can be used to minify arbitrary HTML content, including Javascript and/or CSS.

Some features:

Installation

  1. Add the dependency to your shard.yml:

    dependencies:
      html-minifier:
        github: sam0x17/html-minifier
  2. Run shards install

Minification

require "html-minifier"

HtmlMinifier.minify!("<html>  <body>minify  me!</body></html>") # => "<html> <body>minify me!</body></html>"
HtmlMinifier.minify!("<style>body { background-color: black }</style>") # => "<style>body{background-color:#000}</style>"
HtmlMinifier.minify!("<script> alert('hello world');</script>") # => "<script>alert(\"hello world\")</script>"

Configuration

All options supported by html-minifier on NPM are supported by this shard. Options can be specified by a JSON::Any object or by a JSON string, as shown below.

require "html-minifier"

HtmlMinifier.minify!("<html><!-- comment --></html>") # => "<html></html>"

HtmlMinifier.set_options("{\"removeComments\": false}")

HtmlMinifier.minify!("<html><!-- comment --></html>") # => "<html><!-- comment --></html>"

Note that user-specified options will override their respective default values. The default values for all options are shown below:

{
  "caseSensitive": true,
  "conservativeCollapse": true,
  "minifyCSS": true,
  "minifyJS": true,
  "useShortDoctype": true,
  "removeTagWhitespace": true,
  "removeScriptTypeAttributes": true,
  "removeComments": true,
  "collapseWhitespace": true,
  "collapseInlineTagWhitespace": true,
}