【问题标题】:Grunt htmlmin clean-css breaking my Handlebars code within <style></style> tagsGrunt htmlmin clean-css 在 <style></style> 标记中破坏了我的 Handlebars 代码
【发布时间】:2016-04-01 18:36:47
【问题描述】:

我在我的 Gruntfile.js htmlmin 部分中将 minifyCSS 设置为 true,如下所示:

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

但不幸的是,它现在正在修改我的一些 Handlebars 代码,将其变为:

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

进入这个:

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

...当我真正想要(期待)的时候是这样的:

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

对此有什么快速解决方法吗?否则,我确信我可以以不同的方式重组我的代码

【问题讨论】:

    标签: handlebars.js grunt-contrib-htmlmin clean-css


    【解决方案1】:

    this answer here 的帮助下,我发现html-minifier documentation 中有一个ignoreCustomFragments 选项。使用它,您可以告诉 htmlmin 跳过尝试压缩您的 {{}} 标签,在您的 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
                ...
    

    所以关键部分是添加/{{[\s\S]*?}}/ RegEx。 (当然,如果您愿意,可以将整个 ignoreCustomFragments 数组替换为该正则表达式。)注意:您可能想要转义正则表达式中的花括号“{}”,但如果没有它似乎也可以正常工作.

    更新

    所以实际上,/{{[\s\S]*?}}/ RegEx 似乎在我的代码中留下了一个空格“”......如果我将其更改为 /{{.*}}/,空格将被删除,但我的一些 CSS 样式变得未压缩......所以现在,我认为这两个 RegEx 有点“半解决方案”。我也尝试使用 customAttrSurround as listed in the Wiki 但我什至无法在我的 Gruntfile.js 中使用该代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2021-11-03
      • 2017-09-30
      • 2013-03-29
      • 1970-01-01
      相关资源
      最近更新 更多