How to use an HTML minifier with underscore templa

2019-04-26 22:03发布

问题:

I have some templates for my frontend code, like:

<div class="row">
    <div class="my-header col-md-1">
        <!-- comments -->
        {{ title }}
    </div>
    <div class="my-container col-md-11">
    {% if (content) { %}
        {{ content }}
    {% } else { %}
       <p>Empty</p> 
    {% } %}
    </div>
</div>

And I'm using grunt-contrib-jst to store them all in a single file and then on another build step will be included in a single JS file and that file is pushed to the CDN. This part is working perfectly, but I want to use the processContent option to minify the HTML template code, which contains Undercore template delimiters (<%...%> replaced with {% ... %}, <%= ... %> replaced with {{ ... }}).

I wanted to use html-minifier but it doesn't actually minimize anything, apparently because it tries to parse the template as HTML-only (and fails because of the templating tags).

Is there any Node package / function that allows me to minimize this kind of templates? I would like to use comments and whitespace in source templates but strip everything unnecessary on the resulting build file.

Right now I have this on my JST settings:

processContent: function (content) {
    return content
        .replace(/^[\x20\t]+/mg, '')
        .replace(/[\x20\t]+$/mg, '')
        .replace(/^[\r\n]+/, '')
        .replace(/[\r\n]*$/, '\n');
},
...

But I want to minimize everything possible, that's why I tried with html-minifier.

Thanks!

回答1:

I can't really help with minimising the underscore template delimiters, still trying to find out the best way to do that myself, but you might want to consider running your templates through htmlclean. I use it with r.js and it works really well for stripping out newlines and spaces in the code. Example usage:

var htmlclean = require('htmlclean');

// ...
processContent: function (content) {
    return htmlclean(content)
        .replace(/^[\x20\t]+/mg, '')
        .replace(/[\x20\t]+$/mg, '')
        .replace(/^[\r\n]+/, '')
        .replace(/[\r\n]*$/, '\n');
},

I've had no problems with using this on HTML that has underscore templates in there. I hope it helps you.