Setting up Grunt to compile LESS for Bootstrap 3

  • 07 Mar 2017
  • Matthew Wittering

A tutorial to explain how I setup Grunt on Fedora to compile Bootstrap CSS

I must confess from the outset that it has taken me much longer than I care to admit to setup NodeJS and Grunt on my Linux box to compile the LESS for Bootstrap. Something that I remember being extremely trival with compass for Zurb Foundation SASS's.

After much dispear I found an article published on internetdevels.com entitled, Configuring Grunt for compiling SASS/LESS to CSS.

I think that I'd been going wrong by referring to some perhaps out of date tutorials which promissed to resolve all your workflow problems to compile and minify CSS and JavaScript respectfully.

Start by installing NodeJS. No Fedora, my distribution or choice, this automatically installs npm package manager.

sudo dnf install nodejs

Next we start by installing Grunt's CLI module.

sudo npm install -g grunt-cli

Much like Git we need to start a initialise a new node folder and package.json file. Enter the command below and answer all the questions.

npm init

Now we can install Grunt, the Grunt Watcher and Grunt LESS processor.

npm install grunt --save-dev
npm install jit-grunt --save-dev
npm install grunt-contrib-watch --save-dev
npm install grunt-contrib-less --save-dev

Next I installed Bower in much the same way with.

sudo npm install bower -g

Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies.

We can install Bootstrap with all it's source code with the following command

bower init
bower install bootstrap --save

Once this is complete you'll have a new bower_components directory and bower.json file. Next I setup my gruntfile.json to process the LESS files when changes were detected by the Grunt Watch functionality.

module.exports = function(grunt) {
  require('jit-grunt')(grunt);
  grunt.initConfig({
    less: {
      development: {
        options: {
          compress: false,
          yuicompress: false,
          optimization: 2
        },
        files: {
          "bower_components/bootstrap/dist/css/bootstrap.css": "bower_components/bootstrap/less/bootstrap.less"
        }
      }
    },
    watch: {
      styles: {
        files: ['bower_components/bootstrap/less/**/*.less'],
        tasks: ['less']
      }
    }
  });
  grunt.registerTask('default', ['less', 'watch']);
};

Now we're finished. All that's left is to launch Grunt with this command and watch the output on screen when it completes a task to recompile your LESS into CSS.

grunt watch

References

  1. Configuring Grunt for compiling SASS/LESS to CSS
  2. Using Grunt + Bower with Laravel and Bootstrap
  3. Compiling CSS and JavaScript
  4. Bower - A package manager for the web