Learning GruntJS : Part 3 – Manage CSS Tasks

Earlier we have seen how to get started with GruntJs and JavaScript task management with GruntJs. This tutorial will teach you how to use Grunt for managing CSS tasks. We will go through a number if useful Grunt plugins for managing CSS tasks.

In this series of articles we will learn Grunt basics and also explore a number of important Grunt plugins to automate your front-end workflow. This series covers following tutorials on GruntJs:

1. Learning GruntJs:Part 1 – Getting Started with GruntJs
2. Learning GruntJs:Part 2 – Manage JavaScript Tasks
3. Learning GruntJs:Part 3 – Manage CSS Tasks
4. Learning GruntJs:Part 4 – Some Useful Grunt Plugins

Grunt SASS

Grunt Sass converts SASS files into CSS files.

Install Grunt SASS

$ npm install grunt-contrib-sass --save-dev

Sass Task

Here is sample SASS task to be written in Gruntfile:

// Gruntfile.js
grunt.initConfig({
    sass: {                              // Task
      dist: {                            // Target
        options: {                       // Target options
          style: 'expanded'
        },
        files: {                         // Dictionary of files
          'app/dist/modern.css': 'app/stylesheets/modern.scss',       // 'destination': 'source'
        }
      }
    }
})

grunt.loadNpmTasks('grunt-sass');

Here the files option takes key-value pair as destination-source where all sass files in source are converted into CSS file at destination.

Run Grunt SASS

$ grunt sass

Grunt UnCSS

UnCss is a grunt task for removing unused CSS from your projects. Here are the benefits of UnCss:
New CSS file created
All CSS files referenced in index.html are scanned
Only useful CSS added in the output file

Install UnCss

$ npm install grunt-uncss --save-dev

UnCss Task

Here is sample task for UnCSS:

// Gruntfile.js

grunt.initConfig({
    uncss: {
      dist: {
        options: {
          ignore: ['#added_at_runtime', '.created_by_jQuery']
        },
        files: {
          'app/dist/css/tidy.css': ['app/index.html']
        }
      }
    }
})

grunt.loadNpmTasks('grunt-uncss');

UnCss takes the .html file as input and scnas all the CSS files referenced in it. It then removes the unused CSS from files and merges all CSS files in a single CSS file.

Run UnCss

$ grunt uncss

Grunt Autoprefixer

Autoprefixer parse CSS and add vendor-prefixed CSS properties using the Can I Use database.

Install Autoprefixer

$ npm install grunt-autoprefixer --save-dev

Autoprefixer Task

// Gruntfile.js

grunt.initConfig({
    autoprefixer: {
      options: {
        browsers: ['last 10 versions', 'ie 8', 'ie 9']
      },
      // prefix all files
      multiple_files: {
        src: 'app/stylesheets/*.css',
        dest: 'app/dist/css/'
      },
    },
})

grunt.loadNpmTasks('grunt-autoprefixer');

Autoprefixer takes the broweser versions in options. In the target is takes the source src and destination dest files. According to the browser versions, the source css files are scanned and browser specific prefixes are added at required places. The output is then stored at destination.

Run Autoprefixer Task

$ grunt autoprefixer

CSS Lint

CSS Lint checks your CSS files for possible syntax errors. It will provide a report containing all the possible errors and problems with your code.

Install CSS Lint

$ npm install grunt-contrib-csslint --save-dev

CSS Lint Task

// Gruntfile.js

csslint: {
  strict: {  // first target
    options: {
      import: 2
    },
    src: ['app/stylesheets/**/*.css']
  },
  lax: {  // second target
    options: {
      import: false
    },
    src: ['app/stylesheets/**/*.css']
  }
},

grunt.loadNpmTasks('grunt-contrib-csslint');

In CSS Lint we can create multiple targets according to different options. The src options will take the path of the files to be checked. Running the task will genereate a report of the errors.

Using .csslintrc

You can also create .csslintrc at your project root. This file will contain all the settings and configurations for linting. Here is how to use .csslintrc

// Gruntfile.js

csslint: {
  options: {
    csslintrc: '.csslintrc'
  },
  strict: {
    options: {
      import: 2
    },
    src: ['path/to/**/*.css']
  },
  lax: {
    options: {
      import: false
    },
    src: ['path/to/**/*.css']
  }
},

grunt.loadNpmTasks('grunt-contrib-csslint');

Sample .csslintrc

// .csslintrc

{
  "qualified-headings": true,
  "unique-headings": true,
  "known-properties": false
}

More linting rules/options can be found here.

Run Css Lint

$ grunt csslint

Concat

Concatenation is simple enough and works in a similar way as in case of JavaScript concatenation.

Install Concat Plugin

$ npm install grunt-contrib-concat --save-dev

Concat Task

// Gruntfile.js
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';',
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */',
      },
      dist: {
        src: ['app/stylesheets/main.css', 'app/stylesheets/forms.css'],
        dest: 'app/dist/built.css',
      },
    },
  });

  // Load the plugin that provides the "jscs" task.
  grunt.loadNpmTasks("grunt-contrib-concat");

  // Default task(s).
  grunt.registerTask('default', ['concat']);
};

Run Concat Task

$ grunt concat

CSS min

CSS min minifies the CSS files and reduces the file size.

Install CSS min

$ npm install grunt-contrib-cssmin --save-dev

CSS min Task

// Gruntfile.js

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    cssmin: {
      combine: {
        files: {
          'path/to/output.css': ['path/to/input_one.css', 'path/to/input_two.css']
        }
      }
    }
  });

  // Load the plugin that provides the "cssmin" task.
  grunt.loadNpmTasks('grunt-contrib-cssmin');

  // Default task(s).
  grunt.registerTask('default', ['cssmin']);
};

This task takes key-value pair of destination-source where multiple source files are converted into minified file at destination.

Run CSS min

$ grunt cssmin

Written by Arvind Bhardwaj

Arvind is a Magento and WordPress expert with more than 6 years of industry wide experience.

Website: http://www.webspeaks.in/