If you’re here because you’re wanting a bare bones Grunt Sass starter script for your new project then you’ve come to the right place. This post contains a tutorial with example package.json, .jshintrc and Gruntfile.js files stripped back to just the basics.

This little tutorial will…

  • Help you install the required software
  • Explain how the package.json and Gruntfile.js work (only the basics)
  • Give you a starter template example to copy and use

Background

A few years ago I made the transition from writing plain, arduous and generally lengthy CSS to crafting beautiful, clean Sass. It took me a bit of getting used to – as I’m sure you’re discovering now as to how to get just the basics up and running so you can get coding. A lot of the example I found from other developers were either platform specific (had ties to WordPress structures / files) or were using a LESS. Whilst it becomes really obvious how to write your own Gruntfile as you do it more and more, it’s much better to find just a basic example that’ll get you going and then experiment from there… Well that’s what I find anyway.

Grunt, and in particular writing CSS using the Sass language, is a huge plus so it’s worth giving it a go if you haven’t already. There are lots of advantages that I’m sure you’ve ready about, but for me the most practical ones are:

  • The ability to set global variables for your CSS to reference like $base-link-color, to ability to split your CSS into bite-sized and relevant files that only deal with sections of your website – like a single .scss file for your navigation, or just your dropdown buttons. No longer do you have one huge file that’s crazy to navigate and static.
  • Auto-minification and concatenation of as many CSS and JS files as you like into just two files that are the smallest they can be in file size means you’re giving your page load time a decrease.

Anyway, let’s get started hombre.

Requirements

To get Grunt running you need a few little things installed on your environment (computer). These are:

  1. Nodejs – Think of this as the engine to run Grunt. Download
  2. NPM – Installs the packages for performing the actions you outline in your Gruntfile (comes with Node.js)
  3. Sass – The lifeblood, the language, the mecca. Download
  4. Ruby – Ruby, ruby, ruby, ruby – You just need it (comes pre-installed with Mac’s) Download
  5. Grunt CLI – Let’s you tell Grunt what to do. (We install this via command line)
  6. A command line tool like Terminal or PuTTY.

That should be it. If you find there are errors when you try to follow the steps below it’s usually because you’re computer is missing a dependency. Just copy and paste the error into Google and find the answer ;).

Core Files

Grunt relies on three core files to get you up and running – package.json, .jshintrc & Gruntfile.js. Package.json is like an installer file that you can ‘run’ to download and install the right stuff for the Gruntfile to run on. .jshintrc tells Grunt what types of errors to look for in your code – if it finds errors it will stop running Grunt and let you know. Gruntfile.js is then just a configuration file to choose what to you want your script to do.

Those are the basic files so that’s what I reckon we should focus on. You can add/grow each of these files as you require more from Grunt, but this set up is a good base for beginners.

So, let’s see the code shall we! Note: You can copy paste this code if you know what you’re doing, otherwise I do recommend downloading the source from Github.

package.json

So, let’s quickly take a look at your basic package.json file and what you can expect.

{
  "name": "gruntsassmaster",
  "version": "1.0.0",
  "description": "A super simple Grunt Sass starter example",
  "author": "Andy Crone <[email protected]>",
  "homepage": "http://localhost/ac",
  "repository": {
    "type": "git",
    "url": "git://github.com/andycrone/grunt-sass-starter"
  },
  "license": "MIT",
  "engines": {
    "node": ">= 0.10.0"
  },
  "keywords": [
    "grunt, sass"
  ],
  "devDependencies": {
    "grunt": "0.4.5",
    "grunt-contrib-clean": "0.7.0",
    "grunt-contrib-jshint": "0.11.3",
    "grunt-contrib-uglify": "0.11.0",
    "grunt-contrib-watch": "0.6.1",
    "grunt-contrib-sass": "0.9.2"
  }
}

This an example of a package.json file. Most of it is self explanatory – the main piece to focus on here is the devDependencies section. Essentially, these are the packages that your Gruntfile will use to make magic happen. -jshint and -uglify are JS related, -sass is for reading and processing your Sass code and -watch looks for changes in your code and re-compiles everytime you save a .scss or .js file. Nifty, huh!

.jshintrc

Before jumping into the Gruntfile, there’s a little file you need to include to tell Grunt what code errors to look for. I’ve included the basic stuff, but really unless you have specific code standards you wish to follow, the defaults will be fine.

{
  "curly": true,
  "eqeqeq": true,
  "undef": true,
  "globals": {
    "jQuery": true
  }
}

Alright, that’s enough of package.json and .jshintrc. The fun part is really in your Gruntfile so let’s shimmy over to your shiny new Gruntfile.js and then follow on with a mini tutorial on how to install and setup Grunt.

Gruntfile.js

Ode to be the Gruntfile. Essentially, this file is a configuration file that brings everything together. For the sake of this being a starter template and guide I’ve only included the basics, but rest assured there’s a ton of stuff you can add to this. To be honest though, if you’re a casual frontend / CSS focused developer then you’re not going to need much more than this.

'use strict';
module.exports = function(grunt) {

  grunt.initConfig({
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        'assets/js/**/*.js',
        '!assets/build/app.min.js'
      ]
    },
    sass: {
      dist: {
        options: {
          style: 'compressed',
          compass: false,
          sourcemap: false
        },
        files: {
          'assets/build/app.min.css': [
            'assets/sass/app.scss'
          ]
        }
      }
    },
    uglify: {
      dist: {
        files: {
          'assets/build/app.min.js': [
            'assets/js/**/*.js'
          ]
        },
        options: {
          sourceMap: 'assets/build/app.min.js.map',
          sourceMappingURL: '/assets/build/app.min.js.map'
        }
      }
    },
    watch: {
      options: {
        livereload: true
      },
      sass: {
        files: [
          'assets/sass/**/*.scss'
        ],
        tasks: ['sass']
      },
      js: {
        files: [
          'assets/js/**/*.js'
        ],
        tasks: ['jshint', 'uglify']
      },
      html: {
        files: [
          '*.html'
        ]
      }
    },
    clean: {
      dist: [
        'assets/build/app.min.css',
        'assets/build/app.min.js'
      ]
    }
  });

  // Load tasks
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-sass');

  // Register tasks
  grunt.registerTask('default', [
    'clean',
    'sass',
    'uglify'
  ]);
  grunt.registerTask('dev', [
    'watch'
  ]);

};

To explain a few things:

  • jshint – Looks for code errors in your Javascript
  • sass – Whether to minify your styles and what files to use
  • uglify – Where to find the files to clean up
  • watch – Where to find the files to watch for changes (Sass, JS, Html + any more you like)

The main thing you might want to change here are the source URLs for your Sass and JS files. I always like to keep my raw code clean from production so it pays to keep your Sass in /sass and JS in /js with the files Grunt outputs in your /build folder. That way, you can just link up the two CSS and JS files and you’re away laughing.

Installation

Installing this stuff can be quite tedious at first, but more you practice doing it you’ll start to have your own flow. Step 1 you’ll only have to do once, and chances are you already have these installed.

Install Ruby, Sass & Node.js

Download and install Ruby and follow their installation guide. Same with Sass and Node.js.

Install Grunt CLI

Now that you have Node.js installed you can use a handle package manager called NPM. This bad boy can install a lot of dependencies for you and for us to run Grunt we need their CLI to read grunt commands. In your command line, run the following command to install the CLI.

npm install -g grunt-cli

Copy/paste files

The easiest way to get started is to clone this project from my Github repo which has all the base files already set up and ready go. Alternatively if you already know what you’re doing you can just create/copy and paste the three core files from scratch and use the code snippets above. Remember to get the .jshintrc file for uglify to refer to.

Link up files

Make sure you have linked up the main JS, CSS and livereload files. These are the ones that Grunt will output once it minifies and concatenates your SASS and JS files. For convenience, your HTML might look like:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Grunt Starter</title>
</head>
<body>

<!-- Minified CSS -->
<link rel="stylesheet" href="assets/build/app.min.css">

<!-- Minified JS -->
<script type="text/javascript" src="assets/build/app.min.js"></script>

<!-- livereload -->
<script src="http://localhost:35729/livereload.js"></script>

</body>
</html>

Note, the file structure uses /assets/build/ for the core JS and CSS files, but your working JS and SASS lives in the respective /assets/js/ and /assets/sass/ folders. You can move them, but I personally like keeping things separate. As long as the folder urls match up to your Gruntfile.js then you can freely move things around.

Run Grunt

Now all that’s left is to navigate to your project folder in command line and run grunt to initiate Grunt. This is just to kick things into gear… The real fun occurs when you run…

grunt watch

Now Grunt is actively watching your app.scss file. Go ahead, load up your project in your browser and then add some CSS to the app.scss file and watch grunt auto-create your new JS and CSS files. Easy peasy!

Sass tricks

There are heaps of tricks out there, and I already have some of my own… You can use my up to date Vendor prefixes mixin or a pure CSS loader I built. One of my more popular articles is a Sass based custom checkbox and radio script!

Good luck, if I’ve missed anything just let me know and I’ll fix it up asap :).

The end. But not really...