Grunt is a task runner framework built on top of Node.js. A Grunt-based build typically involves a Gruntfile.js in the root of your project and a couple Grunt plugins installed via NPM.
Default Plugin Template
A Better Plugin Template
I’m not a fan of the single init function. It leaves your code largely untestable and it doesn’t scale well as your task becomes more complicated. I favor a class-based approach that lets us test the code outside of Grunt in an easier fashion. Here is an example of a structure that I use when creating plugins:
You’ll notice from the structure that we’ve separated out the task registration from the actual work being done. The JSHintTask will now hold the logic for our task, and we can require it independent of the task being registered with Grunt.
Now let’s take a look at the shell of our task class.
We pass the original task in to the constructor, which allows us to grab the files and options. In addition, we’ve added some static fields on the class that should help with registration and testing. Now all we need in our task registration file is this:Okay, that’s probably over the top as far as keeping our code separated but I really like keeping that registration file small.
Untested Code is Broken Code
Here is a quick example of how to setup your task for testing.
Now we’ve got ourselves setup on some solid footing and ready to grow as our code needs. I’ll be working on getting this template into a grunt-init version soon, so be on the lookout.
Sign up to have social media resources sent to your inbox every week.
Did you know...
With Sprout Social, you can post to all your social networks from a single window. Queue up content in advance, or let ViralPost find the best send times.
Engineering Team: Front End. Back End. We build new product features, improve existing features, and fix problems identified by our global user-base. From concept to testing to launch day and beyond, all of our engineers participate as active team players in order to meet tight deadlines and deliver for our customers.
Get Social Media Tips Straight to Your Inbox and Become a Better Marketer
You’ll be joining nearly 300,000 marketers who subscribe to Sprout Social’s Insights blog.