Setting up Grunt to compile SASS

By Tyler Crammond, published Wednesday, February 25th, 2015


We use Grunt for all sorts of things at PodPea; from building projects on multiple platforms to bulk image compression. If you’re not familiar with Grunt, it’s an automated task runner with an extensive ecosystem; I recommend checking out their site here.
In this post I’m going to quickly run over how to set up a Grunt task to compile SASS in your project.

Install the grunt-sass plugin

We will be using the grunt-sass plugin. This uses libsass, a C++ SASS compiler.
If you’re using npm you can install it in your project with:

npm install grunt-sass --save-dev         

If you need to use the Ruby compiler for any reason (such as missing features), you’ll need to use grunt-contrib-sass. The configurations are fairly similar, but I can’t promise this post will help you. Sorry!

Set up Grunt configuration

In your Gruntfile, you’ll need to enable the plugin if you aren’t using anything that does this for you automatically:

grunt.loadNpmTasks('grunt-sass');         

Next, we specify some basic settings inside module.exports:

module.exports = function (grunt) {      
 sass: {         
 main: {         
 options: {      
 outputStyle: 'nested',      
 imagePath: '/images'        
 },      
 files: {        
 'app.css': 'app.scss'       
 }       
 }       
 }       
};       
  1. outputStyle – can be nested or compressed. Use compressed for production.
  2. imagePath: – (optional) path to where your images are stored. Allows you to use image-url() and other SASS functions.
  3. files – specify your output and input file(s).

Running SASS the compilation task

Write some real SASS in your input file, run grunt sass:main and you should get some lovely CSS in your output file!
(If you want to, you can include this sass task in your existing tasks with sass:main)
That’s all there really is to it. A link to the full compliment of configuration options is in the list below.