How does grunt uncss task work internally

386 Views Asked by At

I have written grunt uncss task to remove the unused css in my code. But its removing a lot of css which is being used in my code. I guess the reason is, its not checking for css inside the directive 'my-directive' Here is my 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>

Inside my index.css, i have some classes like:

.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;
}

On running grunt uncss task, many of the styles with .peopleeditor class is being removed. Is it because peopleeditor classes will be applied to html tags inside 'my-directive'. Is there any way to read the styling inside directive templates, so that grunt uncss task does not ignore this.

1

There are 1 best solutions below

4
On

There is an ignore option where you can add classes and ids added at runtime, like your directive classes.

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 */

There's also an option, ignoreSheets, to ignore entire stylesheets if necessary.

View the UnCSS docs for more info.

Based on your current Gruntfile.js you'll want to add it like this:

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'
   ]);
};