terser / html-minifier-terser

actively maintained fork of html-minifier - minify HTML, CSS and JS code using terser - supports ES6 code
https://terser.org/html-minifier-terser
MIT License
376 stars 30 forks source link

Feature: Collapse whitespace into a single space #184

Closed nex3 closed 2 weeks ago

nex3 commented 1 month ago

The documentation indicates that this is a desirable feature:

Second option is to never fully remove white space characters, and instead always collapse them to one white space character. HTML 4.01 is actually specified to do just that, so there’s no harm in doing it upfront. Because of this, the following 2 snippets should render identically:

<span>foo</span>

   <span>bar</span>

and:

 <span>foo</span> <span>bar</span>

...with one space in between “foo” and “bar”. Note how in first case, there’s an entire sequence of white space characters (including line breaks).

This second option—collapsing to one white space—has not yet been added to minifier.

But I don't see a tracking issue for it yet.

codemzy commented 2 weeks ago

I think you can do this with:

const { minify } = require('html-minifier-terser');

const result = await minify(`<span>foo</span>

   <span>bar</span>`, {
  collapseWhitespace: true, // removes whitespace
  conservativeCollapse: true, // collapse to 1 space (never remove it entirely)
});
nex3 commented 2 weeks ago

Ah, you're right!