【问题标题】:How does grunt uncss task work internallygrunt uncss 任务如何在内部工作
【发布时间】:2017-10-09 09:09:48
【问题描述】:

我已经编写了 grunt uncss 任务来删除我的代码中未使用的 css。但是它删除了我的代码中使用的大量 css。 我猜原因是,它没有检查指令'my-directive' 中的css 这是我的 index.html:

<div> 
  <span class="duplicate-text" ng-if="duplicateMode" ng-bind-template="{{'html.peopleeditor.duplicate.label'|property}}"></span>
</div>
<div class="peopleeditor col-xs-10 col-sm-10 col-md-10 col-lg-10" id="peopleeditorcontainer">
  <my-directive controller="actionframework.controller" options="options"/>
</div>

在我的 index.css 中,我有一些类,例如:

.peopleeditor .form-horizontal .control-label,
    .peopleeditor .form-horizontal .radio,
    .peopleeditor .form-horizontal .checkbox,
    .peopleeditor .form-horizontal .radio-inline,
    .peopleeditor .form-horizontal .checkbox-inline {
      margin-bottom: 0;
      margin-top: 0;
    }
.duplicate-text {
  font-family: 'Roboto-Bold', sans-serif;
  font-size: 12px;
}

在运行 grunt uncss 任务时,许多带有 .peopleeditor 类的样式被删除。是不是因为peopleeditor 类将应用于'my-directive' 中的html 标签。有什么方法可以读取指令模板中的样式,以便 grunt uncss 任务不会忽略这一点。

【问题讨论】:

标签: javascript css gruntjs uncss gulp-uncss


【解决方案1】:

有一个ignore 选项,您可以在其中添加classes 和ids 在运行时添加,就像您的指令类一样。

ignore (Array): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors:

/* uncss:ignore */
.selector1 {
    /* this rule will be ignored */
}

.selector2 {
    /* this will NOT be ignored */
}

/* uncss:ignore start */

/* all rules in here will be ignored */

/* uncss:ignore end */

还有一个选项,ignoreSheets,可以在必要时忽略整个样式表。

查看UnCSS docs 了解更多信息。

根据您当前的Gruntfile.js,您需要像这样添加它:

module.exports = function(grunt) {

   grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),

      uncss:{
         dist: {
             files:{
                 'dist/index.css' : ['apps/**/*.*']
             },
             options: {
               ignore: ['.peopleeditor'] // Add classes, or regex
             }
        }
      }
   });
   grunt.loadNpmTasks('grunt-uncss');

   grunt.registerTask('default', [
      'uncss:dist'
   ]);
};

【讨论】:

  • 这是我的 github 存储库,我在其中添加了 grunt-uncss 任务:github.com/jasmeen10/Grunt-project 我没有看到忽略不应该删除的选择器列表的选项,因为有很多安静其中。
  • 我已经更新了解决方案,可能会修复您当前的Gruntfile.js
  • 感谢您的解决方案。但我只是假设,指令中的类必须被 grunt 任务充分考虑(因为这些不是用户交互添加的样式)。由于它正在考虑使用 .peopleeditor 类的一些样式并删除一些样式,所以感觉我做的不正确。
  • 不。你没有做错任何事。这些类是通过 JS 添加的。更好的解决方案可能是在 Angular 中添加的所有类前面加上 js- 或类似的东西。然后您可以在ignore 选项中使用正则表达式来忽略任何以js- 开头的类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 2016-03-27
相关资源
最近更新 更多