简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM