Getting started with Grunt and Sass

July 4th, 2013

grunt_sass
There are a lot of new tools out there to help speed up and streamline your workflow as a developer, and to be honest they can seem a bit daunting to get into. Two new tools I have started using this year were Grunt and Sass. Grunt is a commandline JavaScript Task Runner, and Sass is a Css preprocessor that lets you write more powerful css, with the use of variables, mixins/functions and nesting! Lets take a look at getting started using Grunt to compile our Sass.

If you are new to the working in the command line, check my quick overview of some of the basic commands to help get you started.

Dependencies

To get started you will need to install a few things. Ruby to get Sass, and NodeJs to get npm, so we can work with Grunt.

If you are using windows you will have to install Ruby, the Ruby Installer is pretty painless, be sure to check the “Add Ruby executable to your PATH” option. The first time I tried this on a windows machine, I left that alone and could not get it running.

You will also need to grab and install NodeJs, this is pretty straight forward. And instructions for installing both of theses can be found on their sites.

Grunt

Getting started with grunt is pretty simple. You will of course need to install it first. The Grunt site is a great place to get information on installing Grunt if you need more information. But I will just show you that once you have Node install properly you simply run:

npm install -g grunt-cli

This installs the Grunt commandline interface globally to your machine so that you can access it.

Once this is setup there are a few ways to get started.

Option 1:
Using the commandline cd into your projects root directory. If you have an existing project and package.json you can simply run npm install and all the dependencies will be installed.

Option 2:
Lets assume you are starting fresh, running npm init on the commandline from your project root will set up only the package.json file for you.

Option: 3
Or you can set up your own package.json file. Here is a simple example:


{
  "name": "Project Name",
  "version": "0.0.1",
  "devDependencies": {
     //installed packages will go in here
  }
}

For both options 2 and 3 you will need run npm install grunt --save-dev and grunt will be added to your devDependencies in the pacakge.json file. The --save-dev flag saves grunt into your package.json file, this way you can share this file and have everyone on the project using the same dependencies.

More information about the package.json file can be found here.

If you ran npm init, you will need to install grunt and then a few other packages. grunt-contrib-sass, grunt-contrib-watch.

To do this run the command npm install <package> --save-dev. Where <package> is what you need to add. Example npm install grunt-contrib-sass --save-dev

grunt-contrib-sass: This task is pretty straight forward. It is used to actually compile your scss files to css.

grunt-contrib-watch: This is a task that you can run, so that we can watch our folder, whenever a file changes we can configure this task to run other tasks, say compile our Sass files.

Your package.json should now look something like this:


"devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-sass": "~0.3.0",
    "grunt-contrib-watch": "~0.4.4"
}

The other thing that grunt requires, which, is really what does all the work, is the Gruntfile.js. In this file you set up all of your tasks that you will run.

Example:


module.exports = function(grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		sass: {
			dist: {
				files: {
					'style/style.css' : 'sass/style.scss'
				}
			}
		},
		watch: {
			css: {
				files: '**/*.scss',
				tasks: ['sass']
			}
		}
	});
	grunt.loadNpmTasks('grunt-contrib-sass');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.registerTask('default',['watch']);
}

This file starts with a wrapper function and we pass in grunt so that we can access it.

Then you set up the initConfig method for Grunt. In there you set up all your tasks and options for these task. Documentation for the tasks can be found with a simple google search that will usually result in a GitHub page.

Once you have your tasks set up you need to load these. Which is as simple as adding grunt.loadNpmTasks('*Task Name Here*').

We then can register tasks. Do so by adding grunt.registerTask('default',['*tasks you want to run*']); , the 'default' task is what gets run when you type grunt in the commandline, as you can see you also set an array of tasks you want to run when this is done, ['sass','jshint','uglify'].

You can actually set up many tasks, say you want to just have a build step for when you are developing rather then the build step you would use when you publish.

grunt.registerTask('dev',['sass','jshint']);

Running grunt dev will run theses tasks for you.

You may also just call tasks that are in your initConfig. In this case we will just run grunt sass. In your commandline and it will compile your scss to css.

Sass

I will not go into much detail about Sass as there are a ton of great starter posts out there for it. But now that we have our Grunt tasks set up we can simply run grunt from the commandline and go about authoring our Sass and have it compile to Css as we write.

Now why use Grunt over just the standard sass --watch style.scss:style.css way of doing it? Grunt has many more tasks that you can start using and integrating into your workflow, containing that whole process within one tool is pretty powerful.

If you are looking to use compass for you sass, take a look at another post I have, Adding Compass to our Grunt task. If you got this stuff figured out, using compass for you sass should be a snap.

UPDATE:
I just released an article on Getting started with Gulp and Sass if you are interested with an different workflow when it comes to compiling sass.


Warning: count(): Parameter must be an array or an object that implements Countable in /home/ryanch6/public_html/wp-includes/class-wp-comment-query.php on line 405
  • pixelpeitsche

    Thanks for this tutorial. I’ve finally managed to setup my first grunt task =)

  • pburtchaell

    Awesome tutorial man.

  • Pingback: Grunt: Compile LESS/SCSS and Minify CSS/JS |()

  • Pingback: Add Compass to your Grunt task - Ryan Christiani | Front-End Dev()

  • Pingback: Grunt Boilerplate | 易资讯()

  • Bertus Groenewegen

    Great tutorial!

  • Bushwazi

    Thanks. How does one go about adding the –debug-info and –sourcemap flags?

    • Bushwazi

      Answer my own question, for anyone else who ends up here.

      dist: {
      options: {
      style: ‘expanded’,
      debugInfo: true,
      sourcemap: true
      },
      files: {

      • Ryan Christiani

        Sorry for the late reply, glad you could figure it out!

        • Bushwazi

          No worries. Thanks for this article, I’ve referenced it a few times all ready! Even used it to set up a LESS project I inherited.

          • Griffen H. Fargo

            Just wanted to chime in here – for future readers; sourcemap takes a string rather than a bool. If you want to turn them off you’ll need to pass it ‘none’ rather than false.

            Thanks again for the great post!

  • Thomas Hoadley

    Hi! Thanks for the tutorial! I was wondering if you knew how to run these features alongside a foundation 5 libsass project (http://foundation.zurb.com/docs/sass.html). I’m looking to use grunt to compile and livereload my Sass in the browser! It would be awesome if you could give some insight in how to do this!

    • Ryan Christiani

      Hey Thomas,
      There is a libsass grunt task https://npmjs.org/package/grunt-sass , I have not actually used it yet but I would start there, also https://npmjs.org/package/grunt-contrib-watch is now the livereload task. I might explore setting up the livereload option in another post soon. Hope that helps.?!

      • Thomas Hoadley

        Hi, yeah thanks i’ve got it all up and running now!

        • Ryan Christiani

          Hey! That is great!

  • Pingback: Jason Fang's Simple Site()

  • lenymo

    I just want to reiterate the feedback that this was a very helpful tutorial. Thanks!

  • panhna

    thanks that is a good article !

  • http://kevinch.com/ kevin ch

    Hey Ryan, thanks for the tutorial, i’m very new to grunt but it seems awesome once understood.

    One question, i’m trying to get grunt compiling scss files (sass) in my project (https://github.com/babaggeii/Wordpress-Bootstrap3-SASS) but after entering “grunt” in the shell, nothing compiles even if make some changes to some scss files. It keeps on “waiting…”.
    I’ve checked on the dependencies but they’re all installed.
    I know it might not be easy from your position but i’m struggling and i really think that i’m close.
    Thanks.

    • Ryan Christiani

      I think it boils down to your ‘complie’ object. I think you need to have the files being watched as shown here https://github.com/gruntjs/grunt-contrib-sass#example-config where it goes:

      files : { ‘destination’ : ‘source’}

      not

      dest: ‘destination’,
      src: ‘source;

      Does that help?

      • http://kevinch.com/ kevin ch

        I’ll give a look at that solution as soon as i can. Thanks!

      • http://kevinch.com/ kevin ch

        Gave a look but with no luck so far. As said above i’m very new to Grunt. But it seems to me that the problem comes from the watch rather than the compile.

  • pushplaybang

    thanks, this really helped me get going with grunt, if this was in the documentation I would’ve started using this ages ago. Cheers.

  • Monica

    Thanks for the article! Super easy to follow.

  • Octavio

    Thanks a lot for the great tutorial!

    Just a heads up about something that might not be obvious for people just starting on these technologies (like me):

    after installing Ruby and for the grunt-contrib-sass task to work, you have to first install SASS itself with: “gem install sass” 😉

    Source: https://github.com/gruntjs/grunt-contrib-sass

  • Pingback: Getting started with Gulp and Sass - Ryan Christiani - Front-End Developer - Ryan Christiani – Front-End Developer()

  • Bart Veenhof

    So, how do i install the two packages SCSS and watch? Because when i run the commands seperately, i will end up with another Grunt project inside my previously created Grunt project.

  • Railton Santos

    great post! can i use *.sass, how i do it??

    • Railton Santos

      i already solve 🙂

  • Pingback: Sass compilation using Grunt and the role of ruby [on hold] - codeengine()

  • Pingback: Sass compilation using Grunt and the role of ruby [closed] - HTML CODE()

  • keval
  • http://nikscoolstuff.com Nikhil Patil

    Soooo good! Thanks 🙂

  • Ryan Christiani

    Yes, it is in the projects root.

  • Ajay Ramgounda

    I have this issue, for compiling using grunt-contrib-sass, from mutiple sass files to multiple css file. Please check the link: http://stackoverflow.com/questions/43318085/compling-mutiple-sass-files-into-multiple-css-in-gruntfile-js-not-working

  • Andy Durocher

    I have been using this system for years now, and it is straight up the best that I know about to date. However honestly I’ve got some serious complaints about how it compiles, and if anyone out there actually knows please do reply. How can I group media queries together on compile so that the css isn’t so congested with @media text. I have tried combine-media-queries task? This… https://www.npmjs.com/package/grunt-combine-media-queries might be something that goes along the same direction but it does not work for me.

    • Matty Mead

      Why does it matter that the css is congested with media queries? This is what happens when you compile sass.
      CSS doesn’t allow for nesting. sass was written to allow for nesting for cleaner code and less repetition.
      You don’t have to read the css. if you’re debugging, the filename.css.map file should show you which scss/sass file the rules are in. All in all, it’s the browsers job to read the css and render it. When minified, all white space and comments are removed from the css and are usually called filename.min.css
      When this happens, your css code is compiled into around 2 very very long lines as it’s still readable by the browser but saves loading time as the file is smaller… Hope that helps

  • http://www.pandauxstudio.com Zaid Al-Dabbagh

    I last used Grunt a few years ago as I’ve recently been using Webpack, found this tutorial to be great to refresh my knowledge of using Grunt and Sass … Very well written, thanks.