Grunt htmlmin clean-css breaking my Handlebars code within <style></style> tags

214 Views Asked by At

I have minifyCSS set to true in my Gruntfile.js htmlmin section like so:

htmlmin: {
    dist: {
        options: {
            removeComments: true,
            collapseWhitespace: true,
            minifyJS: true,
            minifyCSS: true
...

But unfortunately, it is now mangling some of my Handlebars code, turning this:

<style type="text/css">
{{#each list}}
  .aClassWithBgImage{{@index}}{background-image:url({{images.thumbnailBoxImage}})}
{{/each}}
</style>

into this:

<style type="text/css">{background-image:url({{images.thumbnailBoxImage}})}</style>

...when really what I wanted (was expecting) is this:

<style type="text/css">{{#each list}}.aClassWithBgImage{{@index}}{background-image:url({{images.thumbnailBoxImage}})}{{/each}}</style>

Any quick fixes for this? Otherwise, I'm sure I can just restructure my code differently

1

There are 1 best solutions below

0
D.Tate On

With help from this answer here, I've discovered that there is an ignoreCustomFragments option within the html-minifier documentation. Using it, you can tell htmlmin to skip trying to compress your {{}} tags, using code like this in your Gruntfile.js:

htmlmin: {
    ...
        options: {
            ignoreCustomFragments: [/<%[\s\S]*?%>/, /<\?[\s\S]*?\?>/, /{{[\s\S]*?}}/], //last item in array is the one for Handlebars. The previous 2 items are the default code tags to be ignored, listed in the documentation
            ...

So the key part is adding the /{{[\s\S]*?}}/ RegEx. (You could, of course, just replace the whole ignoreCustomFragments array with that one RegEx if you wanted to.) NOTE: You might want to escape the curly braces '{}' in the RegEx, but it seems to work fine without.

UPDATE

So actually, the /{{[\s\S]*?}}/ RegEx seems to leave a space " " in my code... and if I change it to /{{.*}}/ , the spaces are removed, but some of my CSS styling becomes uncompressed... so for now, I consider these 2 RegExs somewhat of a "half-solution" . I also tried using customAttrSurround as listed in the Wiki but I couldn't even get that code to work at all in my Gruntfile.js .