Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to minify or uglify ES6 Template Strings

Something like

var tpl = `
<div> 
   template
   <span>string</span>
</div>
`

Will produce:

var tpl = "\n<div> \n  template\n  <span>string</span>\n</div>\n";

What I need is to get rid of extra spaces and maybe line breaks, like all other html minification tools do.

So it should become similar to:

"<div>template<span>string</span></div>"

Are there any ways to achieve this wisely and indestructible?

like image 704
Rootical V. Avatar asked Sep 27 '22 00:09

Rootical V.


1 Answers

The best approach is probably using a tagged template, like

var tpl = minifyHTML `
<div> 
   template
   <span>string</span>
</div>
`;

You can start with

function minifyHTML(parts, ...values) {
    var out = [];
    out.push(parts[0]);
    for (var i = 1; i<parts.length; i++)
        out.push(parts[i], String(arguments[i]));
    return out.join("");
}

which is basically the same as with no tag.

Now you can extend that to minify the parts of the template dynamically, so that the tpl will become the expected string.

The next step is to introduce this as a static optimisation in your compile pipeline. Figure out how to write a rule that matches tagged template expressions in the AST where the tag is the identifier minifyHTML, and then evaluate your minification as a part of compiling/bundling the ES6/TypeScript source to the distributed files.

like image 173
Bergi Avatar answered Oct 20 '22 08:10

Bergi