Skip to main content

minify_html

Function minify_html 

Source
pub fn minify_html(html: &str) -> String
Expand description

Collapses insignificant whitespace in HTML.

This is ssg’s own implementation rather than a dependency. Minification rewrites every page the generator emits, so a bug in it is a bug in every site; keeping it in-tree means it is covered by this crate’s own tests and cannot change underneath a release.

What it does not touch:

  • the content of <pre>, <textarea>, <script> and <style>, byte for byte
  • anything between < and >, so attribute values keep their spacing
  • comments, including conditional ones

A previous version bailed out of the whole document if <pre appeared anywhere, and collapsed whitespace everywhere else - including inside <script>, where it silently rewrote string literals. This one tracks which element it is inside, so a page can contain a <pre> block and still be minified around it.

§Examples

use ssg::plugins::minify_html;

assert_eq!(minify_html("<p>  Hello   World  </p>"), "<p> Hello World </p>");

// A script's contents are left exactly as written.
let js = r#"<script>var s = "a  b";</script>"#;
assert_eq!(minify_html(js), js);