Theme development with Grunt: LiveReload, lint, uglify, oh my!
Grunt calls itself "The JavaScript Task Runner." Huh? What's a JavaScript task runner?
The JavaScript part comes from its dependency on using Node.js. The task runner is another way of saying automation. So what we have is an automation tool built on top of Node.js.
What can it do, and why do I need it?
As a Drupal themer/developer, I'm all about being lazy. Lazy in that I don't like doing the same thing over and over again. It compiles & watches for SASS changes. It LiveReloads. It lints, minifies & combines JavaScript and/or CSS files. It copies library assets. It can minify & combine images. Plus tons more. Pretty much any repetitive task can accomplished with Grunt.
Install Node.js/npm & Grunt
First things first. You gotta install Grunt. It is installed from npm (Node.js package manager). Node.js install instructions.
Once Node.js & npm are installed, in a terminal, run (might need to use sudo):
$ npm install -g grunt-cli
Grunt's files
A Grunt project consists of two files: package.json & Gruntfile.js. package.json is used by npm to install the Grunt plugins. The Gruntfile.js (or Gruntfile.coffee if you prefer) is the config file where we setup our tasks. Both of these files should be placed at the root of your theme.
package.json
Start with a simple package.json file, and you can customize it to your specific project:
{<br> "name": "my-project-name",<br> "version": "0.1.0",<br> "devDependencies": {<br> }<br>}
Once this initial stub is in place, you need to add plugins. The easiest way is to run the following:
$ npm install [plugin] --save-dev
where [plugin] is the name of the plugin you want installed. The --save-dev argument tells npm to not only install the plugin locally, but also adds it to the devDependencies section of the pavkage.json file. At the bare minimum, you'll need to install grunt itself as a plugin:
$ npm install grunt --save-dev
The Grunt website has a rather extensive set of plugins you can use. Here's an example of a package.json file I used recently:
{<br> "name": "my-awesome-theme",<br> "version": "1.0.0",<br> "devDependencies": {<br> "grunt": "~0.4.1",<br> "grunt-contrib-compass": "~0.5.0",<br> "grunt-contrib-jshint": "~0.6.2",<br> "grunt-contrib-uglify": "~0.2.2",<br> "grunt-contrib-watch": "~0.5.1",<br> "grunt-contrib-copy": "~0.4.1"<br> },<br>}
Gruntfile.js
Like I said above, the Gruntfile.js is the config file where you setup all your tasks. Here is a Gruntfile.js stub that you can use as a starter:
'use strict';<br>module.exports = function (grunt) {<br> grunt.initConfig({<br> pkg: grunt.file.readJSON('package.json'),<br> });<br>};
Next, you'll add and configure tasks. For this example, I'm using JSHint which validates (lints) JavaScript files.
Here's a Gruntfile.js file with JSHint configured:
'use strict';<br><br>module.exports = function (grunt) {<br><br> grunt.initConfig({<br> pkg: grunt.file.readJSON('package.json'),<br><br> jshint: {<br> options: {<br> jshintrc: '.jshintrc'<br> },<br> all: [<br> 'js/src/*.js',<br> '!js/src/*.min.js'<br> ]<br> }<br><br> });<br><br> grunt.loadNpmTasks('grunt-contrib-jshint');<br><br> grunt.registerTask('default', ['jshint']);<br><br>};
There are three things that were added to the file.
First is the jshint block of code. Within this block is an "options" section that allows you to specify "global" options that will be used anytime the jshint task is invoked. In this case, the jshintrc: '.jshintrc' allows you to specify where the jshint config file is located.
Also in this code block is a "dev" section and a "build" section. The section identifier is simply a way to reference which set of files (or options) to use.
As you'll see below, you can use these set (or target) identifiers like so:
$ grunt jshint:dev
or
$ grunt jshint:build
The next part that was added is the loadNpmTasks()
function. This loads the plugin into Grunt. You'll need to specify each plugin that you use in the Gruntfile.
Finally, the registerTask()
function is used to create chainable tasks. This allows you to create a task that does multiple things at once. For example, with one command, you can lint your JavaScript files, combine them into a single file, then minimize the single file, all the while putting the rendered file in a location completely different from your source files.
Here's a much longer and extensive Gruntfile:
'use strict';<br><br>module.exports = function (grunt) {<br><br> grunt.initConfig({<br> pkg: grunt.file.readJSON('package.json'),<br><br> // Watch for changes and trigger compass, jshint, uglify and livereload<br> watch: {<br> compass: {<br> files: ['sass/{,**/}*.scss'],<br> tasks: ['compass:dev']<br> },<br> js: {<br> files: '<%= jshint.all %>',<br> tasks: ['jshint', 'uglify:dev']<br> },<br> livereload: {<br> options: {<br> livereload: true<br> },<br> files: [<br> 'css/style.css',<br> 'js/*.js',<br> 'images/{,**/}*.{png,jpg,jpeg,gif,webp,svg}'<br> ]<br> }<br> },<br><br> // Compass and scss<br> compass: {<br> options: {<br> bundleExec: true,<br> httpPath: '/sites/all/themes/my-theme',<br> cssDir: 'css',<br> sassDir: 'sass',<br> imagesDir: 'images',<br> javascriptsDir: 'js',<br> fontsDir: 'css/fonts',<br> assetCacheBuster: 'none',<br> require: [<br> 'sass-globbing'<br> ]<br> },<br> dev: {<br> options: {<br> environment: 'development',<br> outputStyle: 'expanded',<br> relativeAssets: true,<br> raw: 'line_numbers = :true\n'<br> }<br> },<br> dist: {<br> options: {<br> environment: 'production',<br> outputStyle: 'compact',<br> force: true<br> }<br> }<br> },<br><br> // Javascript linting with jshint<br> jshint: {<br> options: {<br> jshintrc: '.jshintrc'<br> },<br> all: [<br> 'js/src/*.js',<br> '!js/src/*.min.js'<br> ]<br> },<br><br> // Concat & minify<br> uglify: {<br> dev: {<br> options: {<br> mangle: false,<br> compress: false,<br> preserveComments: 'all',<br> beautify: true<br> },<br> files: {<br> 'js/vendor.js': [<br> 'components/eventEmitter/EventEmitter.js',<br> 'components/eventie/eventie.js',<br> 'components/imagesloaded/imagesloaded.js',<br> 'components/formalize/assets/js/jquery.formalize.js'<br> ],<br> 'js/script.js': [<br> 'js/src/*.js',<br> '!js/src/*.min.js'<br> ]<br> }<br> },<br> dist: {<br> options: {<br> mangle: true,<br> compress: true<br> },<br> files: {<br> 'js/vendor.js': [<br> 'components/eventEmitter/EventEmitter.js',<br> 'components/eventie/eventie.js',<br> 'components/imagesloaded/imagesloaded.js',<br> 'components/formalize/assets/js/jquery.formalize.js'<br> ],<br> 'js/script.js': [<br> 'js/src/*.js',<br> '!js/src/*.min.js'<br> ]<br> }<br> }<br> },<br><br> // Copy files<br> copy: {<br> main: {<br> files: [<br> {<br> expand: true,<br> cwd: 'components/formalize/assets/css/',<br> src: '_formalize.scss',<br> dest: 'sass/partials/vendor/',<br> filter: 'isFile',<br> flatten: true<br> },<br> {<br> expand: true,<br> cwd: 'components/formalize/assets/images/',<br> src: '**',<br> dest: 'images/',<br> filter: 'isFile',<br> flatten: true<br> }<br> ]<br> }<br> }<br> });<br><br> grunt.loadNpmTasks('grunt-contrib-watch');<br> grunt.loadNpmTasks('grunt-contrib-compass');<br> grunt.loadNpmTasks('grunt-contrib-jshint');<br> grunt.loadNpmTasks('grunt-contrib-uglify');<br> grunt.loadNpmTasks('grunt-contrib-copy');<br><br> grunt.registerTask('build', [<br> 'copy',<br> 'jshint',<br> 'uglify:dist',<br> 'compass:dist'<br> ]);<br><br> grunt.registerTask('default', [<br> 'copy',<br> 'jshint',<br> 'uglify:dev',<br> 'compass:dev',<br> 'watch'<br> ]);<br><br>};
There are two tasks that I've created. The "default" task is what I leave running all the time. Since it is the default, you can start it by simply running:
$ grunt
No arguments are required if you create a default task. First, it copies files from third party libraries that I've specified. Next, it checks my JavaScript files for any issues. Then is uses the "dev" section of uglify to combine JavaScript files into a single file. Next it uses the compass plugin to compile all the .scss files. Finally, it starts the watch plugin, which doesn't terminate (until you manually stop it with a Ctrl+C). Any time the "watch" plugin detects a change in one of my .scss files, it runs the compass plugin to recompile .scss partials into .css. It also JSHints whenever a change is saved. And finally (and certainly not least) it LiveReloads the browser.
Whew! That was a lot of things to do. But Grunt handled it marvelously. Pretty cool, eh?
I've also setup a "build" task that can be used when development is completed and you want your files optimized. Run it by also specifying the task like so:
$ grunt build
More info
For more information, please see the getting started page as well as these additional resources.
I've also setup a starter repo over at GitHub that you can use when creating new themes so you can get started quicker.
Have fun!