Contact

Technology

Aug 06, 2014

Modern Web Development Best Practices Powered by Grunt.js Part 4: Automation

Fernando Berrios

Fernando Berrios

Default image background

In the previous part of this series, we left off with a powerful workflow for SASS, CSS, and JS. But it left us with a manual step we have to deal with.

Let’s Add Some Automation, Shall We?

Tutorial:

“git checkout watch” “npm install”

When developing for the web we usually want to see the changes we make as fast as possible, especially with HTML and CSS. The traditional workflow was to make changes to the source files, refresh the browser, test, adjust code, repeat. The problem we face now is we’ve added more steps to the process, and it’s going to kill our productivity. So to get around this issue we will create a few tasks and implement a useful plugin that will let us retain the workflow we are accustomed to. Using the “grunt-contrib-watch” plugin, we added this object to the “grunt.initConfig” section:

watch: { styles: { files: ['sass/*.scss'], tasks: ['compass:dev'] }, scripts: { files: jsAppSourceFiles, tasks: ['concat:dev'] } }

Here, we define two subtasks for the watch plugin, one for the SASS files and another for the application’s JS source files. When this task is executed, a process is launched that will watch for any changes made to the files specified in each of the configurations. Once a change is detected, the tasks defined for that configuration will be run. All you need to do is run “grunt watch,” and leave the process running. The tasks to compile the SASS or JS will run automatically when you make a change. It should look something like this:

Note that you can also run “grunt watch:styles” if you only care about the CSS or “grunt watch:scripts” if you are working only in JS. This type of composability of tasks is one of the features that make Grunt.js such a powerful and flexible task runner.

After implementing all of these workflows and best practices, you should have a very solid base to start building out your app without having to worry about the small yet important details required when the application needs to be shipped. Of course, this was a very simple example meant to aid in understanding the concepts. But you know what? We can do more.

In the rest of the series, we’ll go over some more advanced concepts such as source maps, RequireJS and alternatives, static asset versioning, image optimization, and a few other tricks. We’ll also see how to use more Grunt.js features and plugins to implement them. In the meantime, follow @CrederaMSFT on Twitter and Credera on LinkedIn for more great best practices.

To view the rest of the Modern Web Development Best Practices Powered by Grunt.js series click here.

Conversation Icon

Contact Us

Ready to achieve your vision? We're here to help.

We'd love to start a conversation. Fill out the form and we'll connect you with the right person.

Searching for a new career?

View job openings