Pattern Lab with Grunt and Live Reload

If you haven’t heard of Pattern Lab yet, go check it out. It’s a really cool tool that helps you build atomic design systems. There’s tons of reading over on the official site if you have no clue what any of that means. ๐Ÿ™‚

I can be an efficiency freak, I like everything in my development and build process to be automated. I configured the php version of pattern lab into a node package (which might make some people raise an eyebrow) that allows for some pretty cool features, including:

  • CSS preprocessing (I personally use LESS, but SASS will work too if you make the appropriate adjustments)
  • Live reload

In this tutorial, I’ll walk through basic steps of setting up Pattern Lab with grunt and live reload. No web server needed for this (although you can certainly use one if you want)!

You’ll need:

  • An OS that knows what a proper terminal is ๐Ÿ™‚
  • Git installed on the command line
  • Node.js/npm installed
  • Grunt-CLI installed
  • Slight familiarity with Pattern Lab

I haven’t tested this on a Windows machine, but it should work for Linux/Mac users.

Setting up

If you’ve already set up Pattern Lab, you can probably skip this step.

Open up a terminal window and head to wherever your primary workspace is and clone the patternlab-php repo.

git clone https://github.com/pattern-lab/patternlab-php.git

Now that patternlab-php has a place to live, lets build it for the first time. Your output might look slightly different, but as long as you have no errors, you’re good.

cd patternlab-php
php core/builder.php -g

At this point, you should be able to go to the path you installed patternlab-php in and then navigate to public/index.html and view it. In the case of my example the url would be: file:///Users/jfitzsim/projects/patternlab-php/public/index.html

Now you can edit files in the source/ folder, then rebuild Pattern Lab by running php core/builder.php -g, then refreshing the page to see your changes. If you keep following this article, you’ll eventually be able to edit files in source/ and have your browser automatically refresh with your changes. Before we get there, we’ve got a little work to do.

Nodifying Pattern Lab

Now to keep track of our project dependencies, lets initialize this as a node package. In patternlab-php’s root directory, make a file called package.json and put this in it.

{
  "name": "patternlab-php",
  "version": "0.0.0",
  "description": "- [Pattern Lab Website](http://patternlab.io/) - [About Pattern Lab](http://patternlab.io/about.html) - [Documentation](http://patternlab.io/docs/index.html) - [Demo](http://demo.patternlab.io/)",
  "author": "",
  "license": "MIT",
  "devDependencies": {
  }
}

What we’re currently most interested with is the devDependencies, which are currently blank. These devDependencies will make it easy for you to share your project with your developer colleagues. Once they pull your project down from git, they only need to type npm install and all the devDependencies will be downloaded.

Now it’s time to beef up our project with some grunt plugins. To do anything useful, you’ll want at least grunt-contrib-less (or sass), grunt-shell, and grunt-contrib-watch (I’ll explain later how to add CSS preprocessing). If you don’t put the --save-dev flag on the commands, your package.json file will not be updated with your devDependencies.

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

Quick explanation

grunt-shell will allow us to execute shell commands to automate the building of the patterns that is normally done via command line php.

grunt-contrib-watch will allow us to watch the project for changes then perform whatever task we want (like reload the page, or compile LESS/SASS).

grunt-contrib-less will compile our LESS into CSS. You could use SASS too, grunt is flexible. Do a google search for “grunt sass” and you should be able to find a suitable grunt plugin.

Make your Gruntfile

Now that we’ve installed these grunt plugins, lets put them to work by telling them what to do via our Gruntfile.js. In the patternlab-php root directory, make a new file called Gruntfile.js and put the following in it:

If this is confusing or scary, I highly recommend reading Chris Coyier’s article on grunt which demystifies what is happening here.
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Task configuration.
    shell: {
      patternlab: {
        command: "php core/builder.php -gp"
      }
    },
    less: {
      build: {
        files: {
          "public/css/style.css": "source/less/style.less"
        }
      }
    },
    watch: {
      html: {
        files: [
          'source/_patterns/**/*.mustache', 
          'source/_patterns/**/*.json', 
          'source/_data/*.json',
        ],
        tasks: [ 'shell:patternlab' ],
        options: {
          spawn: false,
          livereload: true
        }
      },
      styles: {
        files: [ 'source/less/style.less' ],
        tasks: [ 'less' ],
        options: {
          spawn: false,
          livereload: true
        }
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-contrib-less');

  grunt.registerTask('default', ['build']);
  grunt.registerTask('build', ['shell:patternlab', 'less']);

};

Now, using grunt-contrib-watch and grunt-shell we can remove one step of having to run that php command. Our watch task will listen for any changes in the directory we specified and when it notices one, it’ll run our build task, which as of right now is equal to running the shell:patternlab task followed by running the LESS task.

Hooking up LESS

The way you structure this is up to you, but here’s the setup I’m working with. This setup is will work with the Gruntfile I provided above.

Screen Shot 2014-04-16 at 2.48.45 PM

Now we’ve got it setup so when you run grunt watch and change your style.less file, it’ll automatically recompile a new CSS file and put it in the appropriate location within public/

Live Reload

Now, lets add in some Live Reload. Download the browser extension of your choice. I’m currently using the Chrome one.

Chrome users: Be sure to enable “Allow access to file URLs” checkbox in Tools > Extensions > LiveReload after installation. Otherwise it won’t work unless you’re running it from a web server.

Run the following command to start up the livereload server: grunt watch

Screen Shot 2014-04-14 at 4.07.16 PM

If it looks like that, it’s working.

Now go into Chrome and turn on your Live Reload client by clicking the icon: Screen Shot 2014-04-14 at 4.09.42 PM

The little circle in the center should fill in it should look like this:

Screen Shot 2014-04-14 at 4.09.02 PM

Now you can open up your style.less file and go to town. Every time you save your .less file, grunt will do the grunt work of building your CSS file.

patternlab-lr

This allows for super rapid development of styles because you can make the changes and then instantly see how it looks. We’ve completely removed the steps of having to re-build our site, go to the browser, and reload. Also, we’re able to live reload new patterns, which is super convenient.

patternlab-lr2

Party

You now have a bad ass (albeit basic) setup to rock out some design systems. The possibilities are very promising and this tutorial has just scratched the surface. For some additional reading:

Thoughts

I’d recommend using a server of some kind. Otherwise, when your Pattern Lab live reloads, you’ll be brought back to the “View All” page. If you’re running it on an apache server, it should save the page you’re on.

Hope this helps people get up and running with this awesome tool.

Why web developers and designers should use Grunt

Work smarter, not harder

The purpose of this post is to help people who are uneasy about using Grunt or other command line tools become aware on what they are missing out on. Chances are, there are a number of reason why you haven’t used these awesome tools that’ll make your life so much easier. I too, was hesitant to use unfamiliar tools, so I hope this post can help ease the transition into being a super efficient web developer/designer.

No knowledge of grunt or node.js is necessary to get something out of this post. If you’re familiar with these tools, you probably don’t even need to read this article. There’s nothing technical in this post, just persuasion points to try to help people to see that they should be working smarter, not harder.

This post if for you if:

  • You find yourself repeating the same mundane tasks over and over while working on a website
  • You put off updating your website because it’s a lot of little time consuming steps
  • You want to take your web development/design to the next level by increasing efficiency (like by minimizing/concating files)

What is Grunt?

Grunt

In very basic terms, grunt is a script that automates mundane tasks. Tasks that you shouldn’t be wasting your time on if you’re a web developer. I mostly use Grunt to minify and concatenate my JavaScript and CSS files, but its capable of so much more than that.

How much of a difference can it really make?

I can actually give a real life example. I worked for an organization who had a website which had 18 separate asset files totaling 508kb. Some of them were CSS, most of them were JavaScript. The website was calling all 18 files individually and none of them were minified. One of my first tasks was to audit these files and see if I could optimize them in any way. They were also using an old version of Bootstrap and wanted to use the latest version because of all the cool new features of Bootstrap 3.

So my mission was get the performance up while not losing any functionality or the way the site looked. I upgraded their framework to Bootstrap 3 which is larger in file size (and which could be a topic for a completely different post because it was kinda tricky) and I reduced the number of requests to 3 files totaling 274kb. That’s a 54% reduction in size and a 600% reduction in server requests.

In a time when more and more of our traffic is coming from mobile devices, this was a pretty big win for us. The only reason I was able to do this in a sustainable way is because I found Grunt to help automate the concatenation and minification of files.

What Grunt allows you to do

Grunt allows you to separate your development files from your production files. This is really quite important and should excite you. This means you can develop the site as you always have, but now you’ll have a buddy named Grunt running in the background, doing the (excuse the pun) grunt work of optimizing files.

Grunt also allows you to easily deploy your websites via FTP or rsync. This will be a subject of a future post. You don’t even need to know how to deploy a website with Grunt to get something useful out of it.

Since Grunt runs on top of node.js, you’ll have access to package management via npm (node package manager). This is pretty cool and once you get more comfortable with grunt, you’ll see how cool it is to be able to install packages from the command line.

I’ve used Grunt with static HTML sites, PHP sites, and WordPress theme development and it hasn’t let me down yet. Grunt is capable of so much, but I’ve only found good use for it as a tool to help me automate my front-end web development.

Are you sold yet?

You should be, but in case you’re not, let me give you a real use case.

For example, say you are developing a site and you have 4 javascript files.

On your site when you call those javascript files, you probably have something in your HTML that looks like this:

<script type="text/javascript" src="scripts/script1.js"></script>
<script type="text/javascript" src="scripts/script2.js"></script>
<script type="text/javascript" src="scripts/script3.js"></script>
<script type="text/javascript" src="scripts/script4.js"></script>

This means your website is going to make 4 requests to the server to load these javascript files. But because you are an efficient web developer, you want to cut these 4 requests down to 1 and minify it so its as small as possible. So if you’re clever, maybe you’ll combine by copying & pasting, all these files into 1 file, then name it script-combined.js and minify it using a tool like this. Then you could load the file like this in your HTML:

<script type="text/javascript" src="scripts/scripts-combined.js"></script>

Now you’d have 4 javascript files combined into 1 file that is minified to be as small as possible. That would be one way to do it, but what about if you need to make updates to script2.js or script4.js?

You have to go through the steps again. Every update would be painful and would require you to perform the same repetitive tasks over and over. This doesn’t have to be the way though. If you’re currently doing development like this, stop it right now and learn these tools. Using grunt, you could literally perform all these tasks with 1 command in your command line or terminal. Now that’s efficient!

All the cool kids are doing it

Organizations like jQuery, WordPress, Twitter, and even WalMart use grunt to help with their web development needs. This is just another point in grunt’s favor of being an awesome, reliable tool. I’m normally hesitant to try out new tools, but when well-known companies and organizations adopt them, I know there must be something there worth checking out.

What’s next?

Be aware that its normal to be hesitant to trying new tools. There is a slight learning curve to picking these tools up, but don’t let that discourage you. You’ll be much better off with them than you were without them. 6 months from now you’ll wonder why it took you so long to check into these. If you’re intrigued and want to give grunt a shot, here’s some awesome links to check out.

The Best Workflow Video I’ve Seen So Far

Paul Irish takes us through a lot of the tools he uses when developing for the web and a very entertaining 56 minute talk. If you find yourself repeating a lot of tedious tasks while developing, this is the video for you to break out of that. This is probably one of the better workflow videos I’ve seen and I’ll be trying 90% of what he described. If you have any other good workflow videos for web developers, please leave a comment below! I’d love to check it out as I’m always trying to improve my workflow.