Getting started with Grunt and Sass

Published in Originals on Oct 18, 2015

This year I’ve started working with some new tools, two of them are Grunt and Sass. Grunt is a commandline JavaScript Task Runner, and Sass is a Css preprocessor allowing you to write more powerful css, with the use of variables, mixins/functions and nesting!

Off we go !

First of all you’ll need to install a few things. Ruby to get Sass, and NodeJS to get npm, so we can work with Grunt.

Grunt

Step one: installing Grunt. If you have NodeJs installed properly you simply run: npm install -g grunt-cli
This will install Grunt globally. So you can use it wherever you want.

Now we need to create the “package.json” file there are several ways to do this. But I prefer to create a new file and input this.

{
	"name": "Project Name",
  	"version": "0.0.1",
  	"devDependencies": {
     	//installed packages 
  	}
}

And then save it as “package.json” in the root of my project.
After that we need to install our Dependencies. This can be done by running the following command:

npm install <package> --save-dev

I want to use Grunt to compile my Sass when I save my project. To do this I need to install 2 dependencies.
grunt-contrib-sass: It is used to actually compile your scss files to css.
grunt-contrib-watch: It watches our folders for file changes.
Example

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

Now my “package.json” looks like this:

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

Next is our “Gruntfile.js”. This file contains the tasks that grunt needs to do for you.

This is how my Gruntfile looks like:

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

Adding tasks with :

grunt.loadNpmTasks('*Name of the task*')

Register Tasks with :

grunt.registerTask('default',['*tasks to run*']);

the default task is what gets running when you type grunt in the commandline.

The end !

When working on your project, just run the grunt command in your commandline in your project folder.

Hit ctrl+c to quit grunt when you’re done.



#gunt, #sass, #css