Visual Studio MVC Bourbon Web App

It is now 2015 and with it a new version of Visual Studio that includes tools for Bower front end package management, Node Package Manager (NPM) and the Grunt JavaScript Task Runner. Not surprisingly, Microsoft has its own way of implementing Grunt, Bower and Node Modules in their upcoming Visual Studio debut. You don’t have to wait for Visual Studio 2015. Grunt, Bower, Node Modules and Bourbon can easily be included in a Visual Studio 2012 MVC 4 web application.

1. Create a New Project

New ASP.NET MVC 4 Web Application – MvcAppBourbon
New ASP.NET MVC 4 Web Application – MvcAppBourbon

2. Select the Empty Project Template

New ASP.NET MVC 4 Project – Empty Project Template
New ASP.NET MVC 4 Project – Empty Project Template

3. Ruby and Sass 3.3+

To install or update Sass you will need to have Ruby installed. For Windows, you can use the RubyInstaller for Windows. See this post for more info, Compass on Windows. These next step are done using a CLI, Windows PowerShell is what I will be using here. Git for Windows provides BASH emulation which also works great.

Install Sass

Ruby uses Gems to manage its code packages, to install the Sass Ruby Gem, enter gem install sass in the CLI.

Windows PowerShell – Install Sass
Windows PowerShell – Install Sass

4. Node Package Manager (NPM)

Install Node.js

NPM is included with Node.js. The best way to install NPM is to install node. The easiest way to install Node.js for Windows is with the Windows Installer (.msi) avaialble here.

5. Bower

Use NPM to install Bower globally on your system.

Install Bower
# global bower install
npm install -g bower

Change to the directory where you app is located. For me this is:
cd ‘~\Documents\Visual Studio 2012\Projects\MvcAppBourbon\MvcAppBourbon’

Install Bourbon
# bourbon install
bower install bourbon

Installed packages are located in the bower_components directory. This is created in the folder which the bower program was executed.

Install Bourbon Neat

Neat is a lightweight semantic grid framework for Sass and Bourbon.

# bourbon neat install
bower install neat

6. Bitters

Install Bourbon Bitters

Bitters jump start projects with a predefined set of basic Sass variables, default element style and project structure. Bitters are not installed with bower since the styles and variables are intended to be customized as needed. Change to the root directory of the app if not already there from bourbon install above. For me this is:
cd ‘~\Documents\Visual Studio 2012\Projects\MvcAppBourbon\MvcAppBourbon’

# bourbon bitters install
gem install bitters

# create a directory for sass files and folders
# this is done from within the MvcAppBourbon app root

mkdir sass

# change to the new sass directory
cd sass

# install bitters into the sass folder
bitters install

# navigate back to the MvcAppBourbon app root
cd ../

# create a directory for css files
mkdir css

Bitters files are installed to base/base. In-depth instructions on GitHub.

7. Grunt

Install Grunt

Use NPM to install Grunt’s command line interface (CLI) globally on your system. Then use NPM init to create a package.json that stores node package data for the app. The third command to run, npm install grunt –save-dev installs the latest version of Grunt into the project and adds it to the package.json devDependencies. More info is avaialable here.

# grunt CLI install
npm install -g grunt-cli

# create package.json
npm init

# grunt install to app, updates package.json
npm install grunt --save-dev

Installed npm packages are located in the node_modules directory. This is created in the folder which the npm install program was executed.

Install Grunt Plugins

The Grunt task that handles sass compilation to css when a .scss file is updated and saved is accomplished with these two plugins, grunt-contrib-watch and grunt-contrib-compass.

# grunt-contrib-watch install
npm install grunt-contrib-watch --save-dev

# grunt-contrib-compass install
npm install grunt-contrib-compass --save-dev
Create Gruntfile.js

In Visual Studio > Solution Explorer;
Right click MvcAppBourbon;
Select: Add > New Item > JavaScript File;
Name: Gruntfile.js

Add this JavaScript to the Gruntfile.

Gruntfile.js
'use strict';

module.exports = function(grunt) {
	// Project configuration.
	grunt.initConfig({
	    pkg: grunt.file.readJSON('package.json'),
	    compass: {
	      dist: {
	        options: {  
	          cssDir: 'css/',
	          sassDir: 'sass/',
	          outputStyle: 'compressed'
	        }
	      }
	    },
	    watch: {
			css: {
				files: '**/*.scss',
				tasks: ['compass']
			}
	    }
	});

	// Load the plugins.
	grunt.loadNpmTasks('grunt-contrib-compass');
	grunt.loadNpmTasks('grunt-contrib-watch');

	// default task
	grunt.registerTask('default', ['watch']);
}

8. SassyStudio Extension

In Visual Studio 2012, select Tools > Extensions and Updates

Search for and install the SassyStudio extension. This free utility provides a small amount of support for .scss files in Visual Studio. More info

9. Sass

In Visual Studio Solution Explorer;
Select Show All Files;

Show All Files – MvcAppBourbon

Right click sass > Include In Project;

Include In Project – MvcAppBourbon

Open sass/base/_grid-settings.scss and change the import path: @import “neat-helpers” to @import “../../bower_components/neat/app/assets/stylesheets/neat-helpers”.

_grid-settings.scss
//not in Rails
@import "../../bower_components/neat/app/assets/stylesheets/neat-helpers";
Create main.scss

In Visual Studio > Solution Explorer;
Right click MvcAppBourbon > sass;
Select: Add > New Item > SASS File;
Name: main.scss

Add this Sass to the main.scss file to import Bitters (base/base) and Neat. Neat is imported after Bitters.

main.scss
@import "../bower_components/bourbon/app/assets/stylesheets/bourbon.scss";
@import "base/base";
@import '../bower_components/neat/app/assets/stylesheets/neat';

Prior to making anymore Sass edits, in the CLI, load grunt to watch and compile changes.

Windows PowerShell – Grunt
Windows PowerShell – Grunt

Since we are using Neat, uncomment the grid-settings import in sass/base/_base.scss:

_base.scss
// Neat Settings -- uncomment if using Neat -- must be imported before Neat
@import "grid-settings";

After saving sass/main.scss, the running grunt tasks should should indicate that css/main.css has been written in the CLI and css/main.css should be updated to contain all of the base styles from the bitters import. Refresh Solution Explorer to see the new css.

Windows PowerShell – Grunt Compass
Windows PowerShell – Grunt Compass

On the next page, controller, views and some Bourbon Refills added for demonstration.

Resources

WordPress Theme Javascript Optimization

This post shows how to combine and minify multiple javascript files in a WordPress theme into one javascript file. The benefit is a single request to a javascript file that has been compressed by minification instead of multiple request to larger javascript files.

package.json

The package.json file contains meta data about your app or module and it includes the list of dependencies to install from Node Package Manager (NPM) when running npm install. NPM is bundled with Node.js; if you have not done so already, install Node.js so you have it. Then create and save this file in your themes root directory, for example /wp-content/my-theme/package.json. Then when you run npm install, the package.json file is read and the respective node modules are installed. More information is available here.

/* package.json */
{
  "name": "my-theme",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-jshint": "~0.10.0",
    "grunt-contrib-uglify": "~0.6.0"
  }
}
# install node_modules
$ npm install
gruntfile.js

The Grunt Javascript Task Runner will be used to configure and run the minification of /js/src/*.js into /js/main.js using UglifyJs.

/* gruntfile.js */
module.exports = function(grunt) {
  'use strict';
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      build: {
        files: {
          'js/main.js': ['js/src/*.js']
        }
      }
    }
  });
  // Load the plugin
  grunt.loadNpmTasks('grunt-contrib-uglify');
  // Default task(s).
  grunt.registerTask('default', ['uglify']);
};
file structure

Here is what the themes javascript file structure looks like for this example. The /js/src folder contains all of the individual javascript files for your theme. When you run grunt, these are all combined and minified into /js/main.js

javascript file location
Partial view of themes files showing location of javascript
functions.php

The functions.php file controls the loading of the themes javascript resources. In the functions.php file, the wp_enqueue_script() function links the script to the page. The pre-existing wp_enqueue_script() function calls are no longer valid since the javascript files have been moved to the /js/src/ folder. Here is an example of the code from the pre-existing functions.php that was linking the scripts:

function my-theme_scripts() {
  wp_enqueue_style( 'my-theme-style', get_stylesheet_uri() );

  wp_enqueue_script( 'my-theme-deflist', get_template_directory_uri() . '/js/deflist.js', array('jquery'), '20141011', true );

  wp_enqueue_script( 'my-theme-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true );
  
  wp_enqueue_script( 'my-theme-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20130115', true );

  if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
	wp_enqueue_script( 'comment-reply' );
  }
}
add_action( 'wp_enqueue_scripts', 'my-theme_scripts' );

Here is an example of the code from functions.php after making the changes to link /js/main.js instead. Since /js/src/deflist.js depends on jQuery, so does /js/main.js and the $deps array parameter is set to ‘jquery’. For more information, refer to the wp_enqueue_script function reference

function my-theme_scripts() {
  wp_enqueue_style( 'my-theme-style', get_stylesheet_uri() );

  wp_enqueue_script( 'my-theme-main', get_template_directory_uri() . '/js/main.js', array('jquery'), '20141011', true );

  if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
	wp_enqueue_script( 'comment-reply' );
  }
}
add_action( 'wp_enqueue_scripts', 'my-theme_scripts' );

Time to Grunt

Run Grunt when you are ready to create or overwrite /js/main.js

# run the default task(s)
$ grunt

Resources

Bourbon

This post is not about a barrel-aged distilled spirit made primarily from corn. Instead, it is about a Sass mixin library. To add Bourbon to your web project, visit the Bourbon GitHub repo and take a look at the requirements.

The first requirement is obviously Sass, since this is a mixin library for it. As of this post, the latest Bourbon requires Sass 3.3+. To install or update Sass you will need to have Ruby installed. Ruby comes pre-installed on OS X. For Windows, you can use the RubyInstaller for Windows. When I set this up last year, I used the Ruby 1.9.3 installers. These next step are performed using a CLI. Git for Windows provides a BASH emulation that you can use instead of the Command Prompt.

Sass check / update

# version check
$ sass --v
Sass 3.2.12 (Media Mark)

# update
$ gem update sass
Updating installed gems
Updating sass
Fetching: sass-3.4.5.gem (100%)
Successfully installed sass-3.4.5
Gems updated: sass
Installing ri documentation for sass-3.4.5...
Installing RDoc documentation for sass-3.4.5...

Install Bourbon

Option 1

The installation as documented at the bourbon repo is pretty straight forward.

# Bourbon gem install
$ gem install bourbon
Fetching: thor-0.19.1.gem (100%)
Fetching: bourbon-4.0.2.gem (100%)
Successfully installed thor-0.19.1
Successfully installed bourbon-4.0.2
2 gems installed
Installing ri documentation for thor-0.19.1...
Installing ri documentation for bourbon-4.0.2...
Installing RDoc documentation for thor-0.19.1...
Installing RDoc documentation for bourbon-4.0.2...

# change to your project directory
# e.g., cd ~/mywebsite
# install Bourbon into your project
$ bourbon install
Bourbon files installed to bourbon/
Option 2

A good alternative is to use Bower to install Bourbon and manage packages for your project. You will need to have the Node Package Manger (NPM) which is bundled with Node.js. If you have not done so already, install Node.js. Then, use the NPM to install Bower

# global bower install
$ npm install -g bower

Next, using bower init, generate a bower.json file for your project. You will be prompted for answers to generate the file. Answering each is up to you, accept the defaults by selecting enter. After the bower.json file is created in your project, install Bourbon using bower install –save bourbon:

# change to your project directory
# e.g., cd ~/mywebsite
$ bower init
? name: BourbonTutorial
? version: 0.0.1
? description:
? main file:
? what types of modules does this package expose?:
? keywords:
? authors: jimfrenette <jim@jimfrenette.com>
? license: MIT
? homepage:
? set currently installed components as dependencies?: Yes
? add commonly ignored files to ignore list?: Yes
? would you like to mark this package as private which prevents it from being accidentally published to the registry?: No

{
  name: 'BourbonTutorial',
  version: '0.0.1',
  authors: [
    'jimfrenette '
  ],
  license: 'MIT',
  ignore: [
    '**/.*',
    'node_modules',
    'bower_components',
    'test',
    'tests'
  ]
}

? Looks good?: Yes

# install Bourbon into your project using Bower,
# this command installs the package and the --save option
# adds the dependency to the bower.json file

$ bower install --save bourbon
bower cached        git://github.com/thoughtbot/bourbon.git#4.0.2
bower validate      4.0.2 against git://github.com/thoughtbot/bourbon.git#*
bower install       bourbon#4.0.2

bourbon#4.0.2 bower_components\bourbon

Using Bourbon

Now we can create a Sass file and test drive some Bourbon mixins. Create a folder named sass in your web project root. And in that folder create a main.scss file with the code/text editor of your choice. Add the following Sass code to your new main.scss file and save it. NOTE: if you used option 1 to install Bourbon, adjust your import path as needed since /bower_components unavailable.

main.scss
@import "../bower_components/bourbon/dist/_bourbon.scss";

button {
    @include button(shiny, #ff0000);
}

Next, create a folder name css for you compiled sass output. Your directory structure should now look something like this depending on which Bourbon install option you used.

option 1
# | bourbon/
# | css/
# | sass/
#     | -- main.scss
 
option 2
# | bower_components/
#     | -- bourbon/
# | css/
# | sass/
#     | -- main.scss
# | bower.json
Setup sass to compile main.scss automatically

From within your projects sass folder, execute the sass watch command. Whenever your main.scss file is saved, the respective main.css will be written with all of the applicable browser extensions, reusable properties, etc..

# change to your sass folder in your project directory
# e.g., cd ~/mywebsite/sass

$ sass --watch  main.scss:../css/main.css
>>> Sass is watching for changes. Press Ctrl-C to stop.
←[32m      write ../css/main.css
←[0m←[32m      write ../css/main.css.map
←[0m

Here is what your /css/main.css file should look like after the Sass compile.

button {
  border: 1px solid #8a0000;
  border-bottom: 1px solid #810000;
  border-radius: 5px;
  box-shadow: inset 0 1px 0 0 #ff1d0c;
  color: white;
  display: inline-block;
  font-size: inherit;
  font-weight: bold;
  background-color: #ff0000;
  background-image: -webkit-linear-gradient(top, #ff0000 0%, #c70000 50%, #a90000 50%, #b00000 100%);
  background-image: linear-gradient(to bottom,#ff0000 0%, #c70000 50%, #a90000 50%, #b00000 100%);
  padding: 7px 18px;
  text-align: center;
  text-decoration: none;
  text-shadow: 0 -1px 1px #730000; }
  button:hover:not(:disabled) {
    cursor: pointer;
    background-color: #f20000;
    background-image: -webkit-linear-gradient(top, #f20000 0%, #bd0000 50%, #a20000 50%, #a90000 100%);
    background-image: linear-gradient(to bottom,#f20000 0%, #bd0000 50%, #a20000 50%, #a90000 100%); }
  button:active:not(:disabled), button:focus:not(:disabled) {
    box-shadow: inset 0 0 20px 0 #900000; }
  button:disabled {
    opacity: 0.5;
    cursor: not-allowed; }

/*# sourceMappingURL=main.css.map */

This is just the tip of the iceberg. With Sass, you can develop modular, reusable styles in small chunks to help make your CSS DRY and organized.

Bourbon Neat with Bitters

Neat is a lightweight semantic grid framework for Sass and Bourbon. Bitters is a set of Sass styles, variables and structure for Bourbon projects.

Going to change gears a little here and use Grunt to handle the watch & compile task for the Sass (.scss) files. Therefore, create this package.json file for NPM in the project root.

package.json
{
  "name": "bourbon-tutorial",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-compass": "~1.0.1",
    "grunt-contrib-watch": "~0.6.1"
  }
}

Using Bower install Option 2, your file structure should look like this:

# option 2
# | bower_components/
#     | -- bourbon/
# | css/
# | sass/
#     | -- main.scss
# | bower.json
# | package.json

From the project root directory, run the NPM install which will add the grunt node modules to the project specified in package.json

# install node modules 
$ npm install

Install Neat and Bitters

# install neat using Bower,
# this command installs the package and the --save option
# adds the dependency to the bower.json file

$ bower install --save neat

# install bitters
$ gem install bitters

# add the library to the project,
# change to the sass directory,
# e.g., cd sass
$ bitters install

A base directory will be created in /sass containing the Bitters library. Detailed instructions are available here.

Create Grunt config

A Grunt configuration file is needed to run the watch and compile tasks. Create this gruntfile.js in the project root.

gruntfile.js
module.exports = function(grunt) {
  'use strict';
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    compass: {
      dist: {
        // these options will override (or extend) config.rb settings.
        options: {  
          cssDir: 'css/',
          sassDir: 'sass/',
          outputStyle: 'compressed'
        }
      }
    },
    watch: {
      css: {
        files: '**/*.scss',
        tasks: ['compass']
      }
    }
  });
  // Load the plugins.
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  // Default task(s).
  grunt.registerTask('default', ['watch']);
};

Run grunt

$ grunt
Running "watch" task
Waiting...

Step 2

This tutorial is not using Ruby on Rails, so edit sass/base/_grid-settings.scss changing the import path as needed for neat-helpers.

_grid-settings.scss
//not in Rails
@import "../../bower_components/neat/app/assets/stylesheets/neat-helpers";

Edit sass/main.scss to import Bitters (base/base) and Neat. Neat is imported after Bitters.

main.scss
@import "../bower_components/bourbon/dist/_bourbon.scss";
@import "base/base";
@import "../bower_components/neat/app/assets/stylesheets/neat";

button {
    @include button(shiny, #ff0000);
}

UPDATE – Bourbon 4.1 path changes **

main.scss
// note changes to path in Bourbon 4.1
@import "../bower_components/bourbon/app/assets/stylesheets/_bourbon.scss";

** Bourbon 4.1.0 released on December 30, 2014
For Bower users, the Bourbon’s directory structure has been changed. Instead of a dist directory, which was just a duplicate of the entire Bourbon library for Bower to use, now point Bower to app/assets/stylesheets.

Bitters is a scaffold of scss files to get you started, add to or edit them as needed. Since we are using Neat, uncomment the grid-settings import in base/_base.scss:

_base.scss
// Neat Settings -- uncomment if using Neat -- must be imported before Neat
@import "grid-settings";

After saving sass/main.scss, per the running grunt tasks the terminal output should indicate that css/main.css has been written. css/main.css should be updated to contain all of the base styles from the bitters import.

>> File "sass\main.scss" changed.
Running "compass:dist" (compass) task
    write css/main.css (0.875s)

Done, without errors.
Source Code

Resources

Bootstrap Customization

This tutorial covers using Git to clone, branch and merge the latest Bootstrap source code, modifying and compiling your modifications to the source LESS variables using Grunt and viewing your compiled changes with a local Node.js web server.

If you are not familiar with Git, Node.js and Grunt, please read my previous post, Grunt JavaScript Task Runner to help get you started.

You could just use the Bootstrap customize and download form to customize the LESS variables and download a pre-compiled Bootstrap package. However, as of this writing, the user interface at the form doesn’t provide a preview option to monitor your changes before you download the package. And since the Bootstrap version 3 source now includes Grunt, we can use it to compile the LESS source and preview the changes via localhost.

Source Code

Using Git, clone the Bootstrap repository. To keep our changes to the source separate and to make upgrading the bootstrap source easier, create a develop branch.

# git clone creates the bootstrap directory in your current directory
$ git clone https://github.com/twbs/bootstrap.git

# create and checkout develop branch
$ git checkout -b develop

Load a Bootstrap example

I like to use the Node.js web-server.js that is bundled with the AngularJS tutorial. For example, here is how I start the NodeJs web-server.js that is included in the angular-phonecat repository on GitHub. This example presumes your CLI is in the bootstrap directory and the angular-phonecat repository is cloned to its own directory one level up.

UPDATED 1/4/2014

Repository contents rearranged over the holidays and the examples have been moved to the docs folder. You can always take a look at the latest source on GitHaub.

# directory structure (partial)
# | angular-phonecat/
#   | -- scripts/
#     | -- web-server.js
# | bootstrap/
#   | -- docs/
#     | -- examples/
#       | -- starter-template/
#         | -- index.html
#         | -- starter-template.css

# start the web server from the bootstrap directory
$ node ../angular-phonecat/scripts/web-server.js

Http Server running at http://localhost:8000/

Now open a web browser and go to http://localhost:8000/docs/examples/starter-template/index.html.

Modify LESS variables

Open the bootstrap/less/variables.less file in a text editor and find the @navbar-inverse-color and @navbar-inverse-link-color variables and change their values from @gray-light to @gray-lighter. Also, find @navbar-inverse-bg and change its value to #FF8C00.

Install node modules and compile LESS

The Bootstrap source contains a package.json for node module installation and a fully configured gruntfile.js to run Grunt tasks.

Open another bash window CLI and navigate to the bootstrap directory to install the node modules. After the node modules are installed, run the Grunt dist-css task which compiles the less files to dist/css/ followed by task dist-docs which copies the css files created in the previous task to docs/dist/css/.

# install node modules
$ npm install

# run grunt task to compile less to dist/css/
$ grunt dist-css

# run grunt task to copy to docs/dist/css/
$ grunt dist-docs

Refresh the web browser to see the compiled changes. The navigation bar at the top of the document in the starter template should now be orange instead of black.

Upgrading the source

Since we are only modifying the variables.less file from the source, upgrading is not that difficult. Using Git, merge the newer Bootstrap source master branch into the develop branch we created.

# checkout master branch
$ git checkout master

# get the latest bootstrap source
$ git pull origin master

# checkout develop
$ git checkout develop

# merge master into it
$ git merge master

Grunt JavaScript Task Runner

This tutorial describes how to setup and use the Grunt JavaScript task runner to automate repetitive tasks such as minification and compilation. Grunt is installed using npm, the Node.js package manager. You will also need Git to work with the tagged source code. This makes it easy to reset and compare your working copy of the code at each step. I discovered commit tags while using the AngularJS tutorial.

If you have not done so already, make sure that you have Node.js, Grunt CLI and Git installed. For Windows systems, after installing Git, you may decide to use the Git bash shell for your CLI (command line interface) instead of the Command Prompt.

Install Grunt’s command line interface (CLI) globally.

#install grunt CLI
$ npm install -g grunt-cli

Source Code

Using Git, clone the GruntTutorial repository. This contains all the source code for the tutorial. As you work through the tutorial, you will be instructed to use git to reset the source code so it matches the step at that point. This will revert the source code to it’s original state for the respective tag and thus overwrite any changes you have made to it.

# git clone creates the GruntTutorial directory in your current directory
$ git clone https://github.com/jimfrenette/GruntTutorial.git

# reset to step 0
$ git checkout -f step-00

Step 1: Node.js Package

# reset to step 1
$ git checkout -f step-01

A npm (nodejs package manager) package.json file is added to the project root for npm to read its structure and know what to do when installing it.

Update: 12-20-2014 — Interactively create a package.json file with the npm init command. More information available at the npm cli commands doc.

# create package.json
$ npm init

Grunt and node modules are installed per the package.json dependencies.

package.json
{
  "name": "grunt-tutorial",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-jshint": "~0.6.3",
    "grunt-contrib-nodeunit": "~0.2.0",
    "grunt-contrib-uglify": "~0.2.2"
  }
}

These node_modules are already included in the step-01 source. To verify the process on your own, reset the tutorial source code to step-00 and run these npm install commands:

GruntTutorial – bash
# install the latest Grunt in your project folder
$ npm install grunt --save-dev

# install dependencies per package.json
$ npm install

Step 2: Combine and Minify Javascript files

# reset to step 2
$ git checkout -f step-02

Gruntfile.js is added to root of the project to specify the modules configuration, define tasks and load plugins. This Gruntfile.js specifies an uglify plugin to perform JavaScript minification. The banner option creates a comment on the first line of the minified file that is output. The JavaScript source (src) and destination (dest) paths are set in the build properties. Since our build source path has a wildcard * before the js filename extension, all of the js files in that directory will be minified into a single JavaScript file named grunt-tutorial.min.js as specified in the build destination property.

module.exports = function(grunt) {
  'use strict';
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: 'src/js/*.js',
        dest: 'build/<%= pkg.name %>.min.js'
      }
    }
  });
  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');
  // Default task(s).
  grunt.registerTask('default', ['uglify']);
};

Time to test our Gruntfile.

# run the default task
$ grunt

You should recieve a message like this

Running "uglify:build" (uglify) task
File "build/js/grunt-tutorial.min.js" created.

Done, without errors. 

Step 3: Compass and Watch Plugin Install

# reset to step 3
$ git checkout -f step-03
OS X / Linux

For the Sass compile with the Compass & Watch Grunt plugins, you will need to have Ruby, Sass, and Compass version 0.12.2 or greater installed. Ruby comes pre-installed on OS X.

Windows

For the Sass compile with the Compass & Watch Grunt plugins, you will need to have the RubyInstaller for Windows. As of this writing, use Ruby 1.9.3 installers. These provide a stable language and a extensive list of packages (gems) that are compatible and updated. During the setup, check the option to Add Ruby executables to your PATH. After installing Ruby, install Sass and Compass using the Start Command Prompt with Ruby.

Start Command Prompt with Ruby
Start Command Prompt with Ruby

Install compass and watch Grunt plugins

By running these npm install commands with –save-dev, the package.json file will automatically be updated to include these two new dependencies.

GruntTutorial – bash
# install plugins and update package.json 
$ npm install grunt-contrib-compass --save-dev

$ npm install grunt-contrib-watch --save-dev

Compass and watch Grunt plugins added to the package.json devDependencies.

package.json
{
  "name": "grunt-tutorial",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.2",
    "grunt-contrib-jshint": "~0.6.3",
    "grunt-contrib-nodeunit": "~0.2.0",
    "grunt-contrib-uglify": "~0.2.2",
    "grunt-contrib-compass": "~0.6.0",
    "grunt-contrib-watch": "~0.4.4"
  }
}

Step 4: Sass

# reset to step 4
$ git checkout -f step-04

Sass .scss files added to the source (src) directory and the Gruntfile.

Gruntfile.js
module.exports = function(grunt) {
  'use strict';
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    compass: {
      dev: {
        // http://compass-style.org/help/tutorials/configuration-reference/#configuration-properties
        // these options will override (or extend) config.rb settings.
        options: {  
          cssDir: 'build/css/',
          sassDir: 'src/sass/'
        }
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: 'src/js/*.js',
        dest: 'build/js/<%= pkg.name %>.min.js'
      }
    },
    watch: {
      css: {
        files: '**/*.scss',
        tasks: ['compass']
      }
    }
  });
  // Load the plugins.
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  // Default task(s).
  grunt.registerTask('default', ['uglify', 'watch']);
};

Time to test our Gruntfile.

# run the default task(s)
$ grunt

Step 5: Compile Sass

# reset to step 5
$ git checkout -f step-05

The CLI / Terminal shows the status of the Grunt tasks that are run.

# run the default task(s)
$ grunt

Running "uglify:build" (uglify) task
File "build/js/grunt-tutorial.min.js" created.

Running "watch" task
Waiting...OK

Edit and save one of the Sass (.scss) files. The watch task waits for changes to files and then fires a task. In our Gruntfile, the watch is configured to run the the compass task whenever a .scss file is updated. The compass task is configured to compile the Sass files specified in the sassDir property (src/sass/) and output to the cssDir specified (build/css/).

CLI / Terminal output from changed Sass file.

>> File "src/sass/reset.scss" changed.

Running "compass:dev" (compass) task
overwrite build/css/reset.css (0.02s)
unchanged src/sass/style.scss
Compilation took 0.053s

Done, without errors.
Completed in 0.717s at Sat Nov 23 2013 17:14:57 GMT-0500 (EST) - Waiting...
Source Code
December 2014 — New Page added to cover using a static web server with live browser reloading.