Grunt or GruntJS is a JavaScript task runner. Grunt allows you to automate repetitive tasks like minification, compilation, unit testing and linting.In this tutorial, we are going to use Grunt to compile Sass, a CSS preprocessor.

Create a file called Gruntfile.js. We will add the Sass plugin config to the Gruntfile.js.

// Compile Sass
    sass: {
      options: {
        sourceMap: true,
        sourceComments: false
      },
      dist: {
        files: {
          'css/file.css': 'sass/file.scss'
        }
      }
    }

In the above example, we will compile the file.scss file located in the sass directory to a file.css file located in the css directory.

Remember to change css/file.css with the folder where the output CSS file will be located and the file name to whatever you want. Also remember to change sass/file.scss to where the Sass file is located and the file name of the Sass file that you want compiled.

Have more than one file you want compiled? List the files and separate them using a comma ,.

'css/file.css': 'sass/file.scss',
'css/file2.css': 'sass/file2.scss'

We will also use the watch plugin, to watch files and whenever a Sass file is changed, the sass plugin will run and compile your Sass file(s) automatically without you doing a thing.

watch: {
  sass: {
    files: 'sass/**/*.scss',
    tasks: ['sass']
  }
}

Remember to change the folder sass, which is located on line three (3) of the above code snippet, if your Sass files aren’t located in the sass folder. The folder should be the same as the one you used in the sass plugin config.

Next, we will load dependencies:

// Load dependencies
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-sass');

Lastly, we will run the tasks.

// Run tasks
grunt.registerTask('default', ['sass']);

When all is said and done, the final Gruntfile.js would be:

module.exports = function(grunt) {

  grunt.initConfig({

    // Project configuration
    pkg: grunt.file.readJSON('package.json'),

    // Compile Sass
    sass: {
      options: {
        sourceMap: true,
        sourceComments: false
      },
      dist: {
        files: {
          'css/file.css': 'sass/file.scss'
        }
      }
    },

    // Watch and build
    watch: {
      sass: {
        files: 'sass/**/*.scss',
        tasks: ['sass']
      }
    }

  });

  // Load dependencies
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-sass');

  // Run tasks
  grunt.registerTask('default', ['sass']);

};

Your package.json would have the following dependencies listed:

  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-watch": "~0.6.1",
    "grunt-sass": "^0.18.1"
  }

You can learn more about package.json on Grunt’s getting started guide.