Three simple ways to start a local webserver

When you first start out with web development you're probably opening html files right in your browser. You're probably using relative urls like /styles/style.css  and this is working fine for you. Right up until you're trying to load some files from a remote location and nothing really works anymore. You ask questions online and people tell you "oh just launch a local webserver and use it to access your files". Yeah, easier said that done, right? In this post I will explain three ways to quickly and simply start a local webserver. I'm going to assume you're either using OS X or a version of Linux for this tutorial.

Python

When you're using a Unix based system like Linux or OS X your machine should already have Python installed. Python comes with the ability to start a webserver for you, all you need to know is where your website files are and how to navigate to the in the command line.

Open up your command line and navigate to your website folder. For example: cd ~/Projects/my-website . Now that we are in the website's main folder we can launch the http server:

python -m SimpleHTTPServer

That's it, you should see some output in your terminal like:

Serving HTTP on 0.0.0.0 port 8000

You can now access your website on http://localhost:8000 and loading external files will work just fine. The server you just launched is a static file server so it will not serve up php files for example. It will just serve your html, css and javascript files.

Node.js and http-server

Another way to launch a local webserver is to use Node.js and the http-server package. This server will do the same as what the Python server does, it will serve your static files like html, css and javascript. Let's get this this running, shall we?

First, make sure that you have Node.js installed. If you don't have it installed, go to the Node.js website and follow the instructions there. When you have Node.js set up it's time to install http-server. Open up a terminal window and type:

npm install -g http-server

If this command throws an error at you, try to run it as sudo (sudo npm install -g http-server). When the installation is complete you can navigate to your website folder, for example type cd ~/Projects/my-website if that's where your website is located. To start the server you should type the following command:

http-server

That's all, you should see output like this:

Starting up http-server, serving ./ on: http://0.0.0.0:8080

Hit CTRL-C to stop the server

You now have a local server running at  http://localhost:8080.

Using a LAMP installer

Many webservers in the wild use the LAMP stack. LAMP is short for Linux, Apache, MySQL, PHP. Apache is a webserver, MySQL is a type of SQL database and PHP is a server-side language. If you're not comfortable with the command line or plan to do PHP development I recommend to install this stack on your development machine. A good installer for this is XAMPP. When you have XAMPP installed you get a graphical interface that you can use to start / stop your webserver and database server. XAMPP will also provide you with a folder that it uses to serve your files. So if you want to use this webserver for your project you will have to move that project in to the XAMPP web folder. Your webserver can be accessed through http://localhost .

Other ways

There are plenty of other ways to start webservers or run a local development environment. Especially if you're doing a lot more than just developing some html, css and javascript files. Personally I have used all three of these methods to launch webservers when I needed to quickly test something, so I figured I'd share these. Especially people who are struggling with loading external resources or want to approach the real word a little bit more in their experiments can benefit from these examples.

If you feel like I forgot a method or maybe I forgot to mention something important, send me a tweet.

Mobile-first is a great workflow

One of the first questions a client might ask you when you start talking about his new website site is "Will it be responsive?". And the answer to that question will more often than not be "Yes, it will". Especially now that Google will penalize websites that aren't mobile friendly it's important that you make sure that your site works well on mobile devices. How do you approach responsive webdesign in a good way? Even though I am not a designer I'd say mobile-first.

Different approaches to responsive web design

When you're doing a responsive webdesign there's a couple of ways to do it. Some people use Photoshop and design three different versions of their website, one for mobile phones, one for tablets and one for the desktop. Others just make one of these three and design the rest during development in the browser.

If you only design one of the three big options, which one should it be? And when you start to build the website, where do you start? Do you do the desktop version first since it's easier for you as a developer? Or do you start with the tablet version because it's in the middle of the spectrum? Or do you let the client decide and start with the one that makes them the happiest?

These are just a few of the options you have when you're doing responsive web design, there isn't a way that is forced upon you by anybody and you're free to choose whatever you feel is most efficient. But in practice there seems to be one approach in the development phase that works every time for me. That approach is mobile-first.

What is mobile-first?

Mobile-first means exactly what you probably think it means, it's when you start your process with the mobile phone. Ideally you will start both the design and the development phase by thinking about mobile straight away. My experience is, however, that clients prefer to see designs for how the website will look on a big screen with all the bells and whistles you might add. So designers tend to not really work from a mobile first perspective because they focus on what the client likes to see. This probably doesn't apply to every designer and every client but it does apply to most designers and clients I've worked with.

When you enter the development phase, the approach you take is in your hands, you can decide where to start. And deciding to start mobile first isn't just a matter of preference. There are very valid reasons to approach the development phase from a mobile-first perspective.

Why mobile-first?

When you are building a responsive website there's a lot of things to consider, how does this look on a screen that is X wide? Should module Y be visible on that screen? Thinking about everything for every screen is overwhelming, there's so much going on and you get so little for free when you're building a website. So you're going to have to start somewhere and I prefer that somewhere to be the smallest screen I will develop for.

Constraints

A mobile phone is not only the smallest, but also the most constraint and possibly even the most used device that people use to browse your website with. Obviously this doesn't apply to every website in the world but do not underestimate the amount of mobile browsing people do. Because of these factors it makes sense to first perfect the browsing experience on the small screens.

And since it's also the most constrained browsing experience you will have to focus on the parts of your app that really matter to your users. This will make sure that you don't just add a lot of noise because it might look cool or pretty.

Development speed

If you've made a responsive website before from a desktop first approach you probably noticed that you had to 'undo' a lot of your styling and scripting. I'd like to illustrate this with a little bit of code. The code will take an unsorted list and turn it into a nice navigation bar for the desktop view. On mobile the list will be shown as a list.

.nav-list {
    list-style: none;
    margin: 0;
}

.nav-list li {
    padding: 0;
    display: inline-block;
}

@media (max-width: 600px) {
    .nav-list li {
        display: list-item;
    }
}

Do you notice how we first set .nav-list li  to a non-default value, inline-block  and then on screens smaller than 600 pixels we set .nav-list li  back to it's default value. Let's rewrite this from a mobile-first perspective.

.nav-list {
    list-style: none;
    margin: 0;
}

.nav-list li {
    padding: 0;
}

@media (min-width: 600px) {
    .nav-list li {
        display: inline-block;
    }
}

This is a small example so the difference isn't dramatic but the implications are significant. Instead of adding and removing styles we are simply adding more styles when the screen is at least 600 pixels wide. By taking this approach it's much more clear what's going on and it's also harder to make mistakes.

With the navigation list example in mind, imagine that we want to add a border and some padding to the list items, but only for the desktop view. Let's compare both approaches again, shall we?

desktop first

.nav-list {
    list-style: none;
    margin: 0;
}

.nav-list li {
    padding: 1em;
    border: 1px solid #333;
    border-radius: .5em;
    display: inline-block;
}

@media (max-width: 600px) {
    .nav-list li {
        display: list-item;
        padding: 0;
        border: none;
        border-radius: 0;
    }
}

mobile first

.nav-list {
    list-style: none;
    margin: 0;
}

.nav-list li {
    padding: 0;
}

@media (min-width: 600px) {
    .nav-list li {
        display: inline-block;
        padding: 1em;
        border: 1px solid #333;
        border-radius: .5em;
    }
}

As you can see the mobile first approach is a lot cleaner. Not only is it cleaner, it's also safer. We don't have to worry about resetting certain styles back to their defaults like we have to in our desktop-first approach.

Of course you still have to keep an eye out for cascading accidents because sometimes you set something for mobile that will have to be reset for your desktop view. But in my experience this happens a lot less often with mobile-first than it does with desktop-first.

Adding javascript is easier than removing it

I just showed you that when it comes to css it's a lot easier to stack on more styles than it is to reset them to defaults for mobile. The same applies for javascript. I usually find myself initializing a lot less (complex) modules for mobile. When you take a mobile-first approach with this you will not initialize certain things at first. Once you know that you're on a large screen machine you can start initializing your larger, more complex modules that are intended for desktop use.

Not only is it easier to initialize things when you know you need them, it's also a lot faster. Imagine executing some heavy javascript on a mobile phone only to find out that the module won't even be used because the target elements are hidden. That's a waste of precious resources that you might have used to get your page up and running on the device really quick.

Conclusion

In this post I explained to you what a mobile-first approach is from the perspective of a developer. I also showed you how this impacts the process of writing code. Going in mobile-first will prevent you from having to write a lot of 'reset this to default' css. It's also easier for the javascript part of your application. You won't initialize thing that you don't need and this generally makes your pages render faster as well.

I'm not saying that a desktop-first approach is worst in every case or scenario, I'm also not saying that the design process has to be mobile first. But thinking about the smallest most constrained devices does seem to result in faster and more focused websites. It also seems to lead to a more solid code base and happier developers.

Don’t depend on javascript to render your page.

Today Christian Heilmann posted this tweet, demonstrating a rather huge delay between page load and javascript execution. This huge delay made the page show things like {{venue.title}} for an awkward amount of time. Once the page has loaded for the first time you can refresh it and the {{venue.title}} won't show. What it does still show, however, is a wrong page header (the venue title is missing) and the font isn't loaded straight away either. So I guess we all agree that there's several things wrong with this page and at least one of them is, in my opinion, completely unnecessary.

What's actually going wrong here?

From what I can tell this page is using Angular.js. I'm not going to rant about Angular and what might be wrong with it, there's plenty of other people out there who do that. What I will say, however, is that the approach this website uses to rendering rather simple data is wrong. This website is serving you a webpage from their server. Then the browser has to read that page, load all assets and read them. So the page will only start looking better after all the javascript was loaded and executed. If this sound terrible to you that's because it is.

Not only did Christian post a Youtube video, he also ran the page through Web Page Test. This produced another video that shows the page loading with a timer. It takes six(!) seconds for the correct title to appear in this video. It takes twenty-five seconds for the page to be complete.  For a webpage, six second is a long time, twenty-five seconds is an eternity. People might not even stay on your page for six seconds, let alone twenty-five.

So why is the page this slow? Angular is pretty fast, or at least computers are fast enough to make what Angular does really fast. So something fishy must be going on here. Let's use some inspector tools to find out what this page is doing and where it's spending time at.

Loading the page and assets

When loading the page using Safari with timelines enabled we can see how this page is loading it's assets and how rendering is going on. The first thing I'll look at is the networking section to get an idea of how everything is being loaded.

Schermafbeelding 2015-03-14 om 11.11.42

As you might expect, the browser will first load the page itself. The page is 10KB, which isn't bad. A website like reddit weighs in at about 125KB. Then the styles load, they're about 240KB, rather large. Especially if you consider what the page looks like. Then a 5KB print stylesheet is loaded as well, nothing wrong with that.

And then comes an almost 500KB(!) libraries file. That's huge. Like, really huge. That file alone almost takes a full second to load over my fast cable connection.

At the 577ms mark we start loading the actual information that should be displayed on the page. There's a full second of latency before that file starts loading. And once that file is loaded (and parsed) the title can be displayed. This result is a little different from the web page test, probably because I have really fast internet and a fast machine and maybe a bit of luck was involved as well, but almost two full seconds before anything happens is a long time. That's almost two seconds after the initial page loaded.

What does this mean?

The analysis that I've done above isn't very in-depth, and to make my point it doesn't have to be. What the above statistics tell us that it took the webpage almost two seconds to go from loading html to displaying a rendered page. Not everything on the page was loaded properly yet, it just took about two seconds to go from {{venue.title}} to displaying the venue's actual title. What if I told you that there's no good reason for this to take two seconds or even six seconds in the web page test video? And what if I tell you that I could get that title on the page in about zero seconds?

Doing this better

The title of this article says that you shouldn't rely on javascript to render your page and I believe that the better.org.uk is a perfect example of this. This website could be improved an insane amount if they would just render that initial view on their server. I don't see single valid reason for the server to not pick up that .json file containing the venue info, parse it and put it's contents on the page. Doing this would result in {{venue.title}} not even being in the html at all. Instead it will contain the actual venue title. This goes for all the venue info on the page actually. Why load that after loading the page and all the javascript and waiting for the javascript to be parsed? There are times where you might want to do something like this but that's usually after user interactions. You might want to use javascript to load a list of search results while a user is typing to provide real-time searching for example. But I don't think javascript should be used to load page critical information, that's the server's job.

Wrapping this up

The example I used is a really slow website, not all websites are this slow and some website don't suffer from that flash of {{venue.title}}. But my point still stands for those websites, they are slower than they need to be because they load page critical data after the page is loaded. I want to thank Christian Heilmann for tweeting about this issue and allowing me to use his resources for this post. This issue seems to be a real one and everybody seems to forget about it while they fight over which framework is the best, fastest and most lightweight. Not depending on the framework to render your page is the fastest, best and most lightweight way there is. You can find me on Twitter if you have pointers, corrections or opinions on this. Thanks for taking the time to read this!

Automagically load your Gulp plugins

When I first started using gulp I felt that the most annoying thing about it all was that I had to manually require  all my plugins. So on a large project I would get 20 lines of requiring plugins. Soon I was looking for a solution that would allow me to include plugins automatically and thankfully I found one that's extremely easy to use. It's called gulp-load-plugins.

Using gulp-load-plugins

In order to use gulp-load-plugins you must first install it through npm. Open up a terminal window and type npm install --save-dev gulp-load-plugins if it fails due to permission errors you might have to run the command as sudo . When the plugins is installed you can use it inside your gulpfile like this:

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

gulp.task('scripts', function() {
    gulp.src("/scripts/src/*.js")
        .pipe(plugins.plumber())
        .pipe(plugins.concat('app.js'))
        .pipe(plugins.uglify())
        .pipe(gulp.dest("/scripts/"))
});

On line 2 gulp-load-plugins is being included. Note that we immediately call  this module as well by adding parentheses after requiring it. When you call the plugin it looks through your node_modules  and it adds every module that starts with gulp- to itself as a callable function. So if you have gulp-uglify installed you can just call plugins.uglify .

When you have a gulp plugin that has a name with dashes in it, like gulp-minify-css . The loader will add it as minifyCss . In other words it will camelcase the plugin names. Well, that's it. This gulp plugin really helped my gulp workflow and I hope it will help you as well.

Stop writing vendor prefixes, autoprefixer does that for you

Anybody who writes css for the modern web has probably touched vendor prefixes at some point in time. These prefixes are required to get the most out of browsers that are supporting bleeding edge properties in ways that aren't yet part of the css3 spec. When you’re writing these vendor prefixes it’s easy to forget one or two, or maybe you add one that isn't actually required for the browsers that you’re supporting. Of course you can always check out caniuse.com to check the prefixes you need for your use case but that’s something you don’t want to do on a daily basis.

And even if you knew all the prefixes you probably wouldn't know the syntax for each property. For example, take flexbox. Flexbox uses several implementations across several browsers and writing a full stack of vendor prefixes for it would look a little bit like this:

.flexbox {
    display: -webkit-box;
    display: -webkit-flex; /* two webkit versions!?!?!? */
    display: -ms-flexbox;
    display: flex; 
}
 
.flexbox .flexitem {
    -webkit-flex-shrink: 0;
    -ms-flex-negative: 0;
    flex-shrink: 0; 
}

Using autoprofixer you can just write this and it will output the above prefixes for you:

.flexbox {
    display: flex;
}
 
.flexbox .flexitem {
    flex-shrink: 0;
}

Much better, right?

How does it work?

Autoprefixer uses caniuse.com to figure out what prefixes it should use. When you use autoprefixer you can always define what browser you want to support. You can define the browsers in a very natural way, for example you could pass it > 5%  which tells it to only support browsers that have more than 5% share in the market.

It then scans your entire css for properties that require prefixes and it automatically adds them to your css. Simple enough, right?

Setting this up for yourself

I will use Gulp to set up autoprefixer. If you’re unfamiliar with Gulp, I’ve written a post on getting started with it. I recommend you read that before you continue. If you’ve used Gulp before, grab your gulpfile and open a terminal window.

First of all we should install the gulp-autoprefixer plugin. Do this by typing npm install —save-dev gulp-autoprefixer . If you get permission errors you might have to run this command as sudo (sudo npm install —save-dev gulp-autoprefixer). Now that we have that set up we can add gulp-autoprefixer to our css task like this:

var gulp = require(‘gulp’);
var sass = require(‘gulp-sass’);
var autoprefixer = require(‘gulp-autoprefixer’);
 
gulp.task('css', function(){
    gulp.src('src/sass/**/*.scss')
        .pipe(sass())
        // the important lines
        .pipe(autoprefixer({
            browsers: '> 5%'
        })) 
        .pipe(gulp.dest('contents/css/'));
});

If you already use gulp only lines 9-11 will be important to you. What’s going on here is just a regular css compile task. We take all our .scss files and stream them to the sass plugin so they will be compiled. After doing that we stream the compiled css to the autoprefixer which will add all the vendor prefixes we need. Then the output gets saved and you’re done, you can write prefix-free css now!

A note about the above code

After publishing this I received a note from Andrey Sitnik, the author of Autoprefixer, saying that gulp-postcss should be used over gulp-autoprefixer. Below is an example of using autoprefixer with gulp-postcss. To use this you should first install both packages: npm install --save-dev gulp-postcss autoprefixer-core .

Example code:

var gulp = require(‘gulp’);
var sass = require(‘gulp-sass’);
var autoprefixer = require('autoprefixer-core'
var postcss = require(‘gulp-postcss’);
 
gulp.task('css', function(){
    gulp.src('src/sass/**/*.scss')
        .pipe(sass())
        // the important lines
        .pipe(postcss([
            autoprefixer({
                browsers: '> 5%'
            })
        ])) 
        .pipe(gulp.dest('contents/css/'));
});

The nice thing about using postcss is that you can combine multiple postprocessors. That makes it more powerful that just using gulp-autoprefixer.

How about Bourbon?

Bourbon is a sass mixing library that has many features, one of which is prefixing css. It does this by providing mixins to you that will prefix the css you pass it. An example:

a {
    @include transition(color, 200ms);
 
    &:hover {
        color: blue;
    }
}

When you compile your sass this will output properly prefixed css. The big plus for this is that you have one plugin less in your gulp file because sass (with some help of bourbon) is now prefixing your css. However, you still have to remember what properties use prefixes. That in itself isn’t bad, it’s good to know what you’re working with but it’s also easy to forget to use the mixin and end up with forgotten prefixes.

Wrapping up

In this post I've explained to you, briefly, why you shouldn't be writing your own vendor prefixes. It's easy to forget some and they're high maintenance. I also explained to you that a gulp plugin called gulp-autoprefixer can make your live a lot easier by automagically prefixing css rules that require a vendor prefix.

I also showed you really quick that you can use Bourbon to achieve effectively the same thing but it's a little bit more high maintenance than using autoprefixer.

The main point is, you don't have to write prefixes yourself. There are two very nice tools out there and each has it's own pro's and con's. I personally prefer autoprefixer because it uses caniuse.com to figure out what it should prefix and I can have 0 worries about remembering what properties need prefixing.

You should start using Browsersync today.

Seriously, you should. Browsersync is a great tool that allows you to sync your browser on multiple screens. This might not sound that impressive, but in reality it is. It's so impressive that I felt like I needed to make a .gif for you because you otherwise might not get how awesome Browsersync is.

bs_demo

The above image shows four different browsers, all of them are acting in sync. I am only interacting with the browser on the top right, the other three are automatically updating through Browsersync.

Why should you use it?

Personally, I held off trying Browsersync for quite some time. But when I installed it last Friday I was absolutely amazed, it was so easy and it's such a great tool to test multiple browsers. Even mobile browsers play nice with Browsersync. Integrating it with gulp was extremely simple as well so I can refresh all connected browsers whenever my css or javascript gets compiled. Need more than reloading and syncing? Well, there's more to Browsersync than those two features.

Remote debugging

When you're working on a Linux machine, like I am, and somebody walks up to you with their iPhone and show you a bug it can be a real pain in the arse. Debugging Safari on an iPhone without having a Mac nearby is damn near impossible. With Browsersync it's as easy as connecting the iPhone to Browsersync and you can remotely inspect the DOM, console and more. Isn't that awesome? If that's not cool I don't know what is.

Setting this up for yourself

Let's set up Browsersync for whatever project you're working on right now, shall we? First install Browsersync through npm:

npm install browser-sync --save-dev

Make sure you have gulp installed as well, if you've never used gulp before then you might want to check out my post on getting started with gulp.

In your gulpfile make sure to include Browsersync.

var browserSync = require('browser-sync');

Let's say we want to start Browsersync whenever we start our gulp watch task. And then whenever our css changes we want to refresh the browser. Doing this is actually incredibly simple. Here's the code:

gulp.task('watch', function(){
    browserSync({
        proxy: 'http://localhost:5000'
    });

    gulp.watch({glob: 'scss/**/*.scss'}, ['css', browserSync.reload]);
});

The above code is creating a watch task on line one. Then on line 3-5 we start Browsersync. The only option I'm passing to it is a proxy. In this example I assume you have a current development setup where you're running your app server in a way you're used to. The project I tried Browsersync with is a Python app, so using a proxy is the best way for my own use case. You can also opt for running Browsersync on a folder, it's up to you really. Check out the docs for more options.

When the css changes we start the css task. The next task we pass is the browserSync.reload function. When this function is called all connected browsers will reload. And that's all, you're using Browsersync.

When you start your watch task by typing gulp watch , Browsersync will tell you the url for your project in the console. It also tells you a UI url. This url is where you'll find some great features and debugging options. You should try to explore them a little, they're really nice.

Moving forward

Now that you have Browsersync set up you can start exploring it's great features. The documentation for Browsersync is really good and goes in depth about all the options you can pass to it. The debugger is really powerful and deserves to be used once you start checking everything out. Hopefully you'll enjoy using Browsersync and the way it can speeds up your development workflow.

If you think I've missed anything, if you have questions or feedback, you can find me on Twitter.

Why I love to write stories while I’m programming

When you program something that involves complex logic it's very easy to jump in head first and start typing away. The first couple of projects I did started like this, they weren't very carefully planned out which meant that requirements would change all the time. This often resulted in buggy code and forgotten features.

When I started working with other programmers who were young and inexperienced like I was, I noticed that many of them struggled with the same problems. We would encounter weird bugs all the time and we'd curse those silly users for wanted strange things. The things users want are, in fact, seldom strange. Users might not be able to articulate what they want but more often then not their wishes are genuine and real.

Starting to define projects

When I learned more about programming, I learned that planning and defining requirements is extremely important. So whenever I started working on something I'd start thinking about it. I thought real hard for several minutes before I started to model my data. And then I thought some more and remodeled my data. And I'd think about features, and then I would build them. And I felt great, everything seemed so organized because I actually thought it through.

But then those pesky users came along. Still finding bugs. Still missing features. And I would have to go back to the drawing board, remodel data, break everything I had built just to allow a user to edit something they did before. At this point I had realized that most features users complained about were actually good features. For example, editing something. Users make mistakes, they should be able to correct them. It seemed so logical to me, the system asks you "Are you sure?" and the user responds with a "Yes". The user was sure so why would they need a way to undo it, or edit it. Well, we all make mistakes and a system should be kind to it's users.

Write it down

In order to not forget features I would write down lists at the beginning of a project. Often these lists would be written down really quick and I'd use pen and paper for this. The list would contain features, data flows and they would be written from the perspective of the application. This helped me a lot but it still wasn't perfect. I would still forget about users in a way that was very annoying for myself. And the people that used the things I built were probably a bit annoyed as well.

So, when I got some bug reports in I would quickly write them down, redefine what I was going to do and off I went, fixing bugs and making the world a nicer place. But you can probably already guess. I'd still forget things. I sometimes shared my lists with others to make sure I didn't forget anything. Usually I didn't seem to have forgotten anything until we started some real world testing. So, what went wrong here? I had lists, people gave feedback, all should be good right?

The user story

It wasn't until I started working on a very large, internal project at Rocket Science Studios that I learned how to properly define features. One of the senior developers wanted to approach the big project with user stories. These stories would outline how a user interacts with the application. The stories were never very long and they would never take into account how the system works. So no mention of AJAX or MySQL, just user related actions. A user story we wrote would look like: "When I add a new item to the canvas I want it to be placed in the center automatically". Or "If I move something around I want it to be saved automatically". Or, one more example "When I lose my internet connection I don't want to lose my changes if the browser window closes".

When you have user stories you start working with something real. You start thinking like a user and you start thinking about how a user actually interacts with your application. And when you are in that mindset you probably become more critical of your own work. When a user wants something to happen they probably want it to happen smoothly. They probably don't care about technical details, they just want to do things.

In conclusion

In the years that I have been learning how to build web applications I tried several approaches to building features. I've learned that doing things quickly seldom is a good idea. An even worse idea is to keep all the information in your head. You're probably way too busy to actually remember everything, sometimes over the course of several days. Another thing I've learned is that users don't care about details. A user wants to do something and they want it to be smooth, it's our job to make that happen.

A tool I enjoy using is the user story. This tool is a simple, effective tool that forces you to think from a user perspective rather than an application perspective. This forces you to carefully plan and think about features in a more user centered way. And this often results in making things smoother, more logical and less buggy. So, my advice to anyone out there reading this is to try user stories sometime. Maybe together with your whole team, maybe just for your own features. And chances are that you will write better applications.

How to prevent Gulp from crashing all the time

When you're working with Sass and use Gulp to compile your  .scss files it can happen that you introduce an error by accident. You misspell one of your mixins or variables and gulp-sass will throw an error. When this happens your Gulp task crashes and you have to restart it. When I started using Gulp this drove me crazy and I really wanted a solution for this problem.

Gulp-plumber

The solution I found is called gulp-plumber. This nifty plugin catches stream errors from other plugins and allows you to handle them with a custom handler. You can also let gulp-plumber handle the errors, it outputs them to your console by default. So when a plugin encounters an error you will be notified of the error and you can easily fix it without having to restart your Gulp task.

Example code

gulp.task('scss', function(){
    gulp.src('/**/*.scss')
        .pipe(plumber())
        .pipe(sass())
        .pipe(gulp.dest('/css/'));
});

The above example takes all scss files as input and then 'activates' gulp-plumber. After doing this you can use gulp like you are used to. Whenever an error occurs after activating plumber it will be caught and handled so gulp doesn't crash on you. That's it, hopefully this is helpful to you. If you have questions about this quick tutorial you can find me on Twitter.

How I improved my workflow with Imagemagick

When working with assets you will often want to change some of them. My personal experience is that I often want to resize images, stitch them together, blur them or convert them from .png to .jpg. When I had to do this I usually sighed, fired up Photoshop, created a batch and then ran everything in my folder through that batch. When I realized I got it wrong I would have to do this again and Photoshop usually crashed at least once in the process as well. Needless to say, I did not enjoy adjusting my assets. Until I didn't have Photoshop anymore...

Changing workstations

In december I switched from an OS X oriented workplace to an Ubuntu oriented workspace which meant that I didn't get to have Photoshop on my machine (without jumping through hoops). This wasn't a problem because I didn't have to work with assets as much as I used to and when I did I would just ask somebody else to do the tedious tasks for me.

But then I remembered Imagemagick. In the past I've used their PHP library to resize images on my webserver, but under the hood that actually uses the Imagemagick command line tool. And since I was working with a Linux machine I figured I could install Imagemagick and use it. And so I did. And it's beautiful.

Start using Imagemagick

Before you can use Imagemagick you have to install it, go to their install page and find the appropriate version for your machine. Surprise, it turns out they have an OS X version as well. After you've installed Imagemagick you should prepare some images to resize.

Resizing images

Resizing images is surprisingly simple. Open up a command line, navigate to the folder where you have your image and type this into your command line.

convert myimage.jpg -resize 50% myimage_half_size.jpg

This will scale your image down to 50% of it's original size. If you have several images to do this with you might run something like:

for "x" in *.jpg; do convert $x -resize 50% half_size_$x; done;

Pretty simple, right? You can also scale images proportionally to a pixel value like this:

convert myimage.jpg -resize 250x myimage_250.jpg

This will make the image 250px wide and scale the height proportionally. Scaling an image based on height is similar but place the pixel value after the x:

convert myimage.jpg -resize x250 myimage_250h.jpg

Manipulating image quality

After resizing your images you might want to optimize their quality a bit as well. I usually get extremely high quality assets and they can be as large as 2-3Mb sometimes. After resizing they might already be around the 100Kb, but giving up a little quality can take them down to 60-70Kb. Here's the command to do that:

mogrify -quality 60 myimage_lq.jpg

Instead of convert I used mogrify for this snippet. Mogrify is used for in-place manipulating of images, so it overwrites your image. If you don't want this you can just substitute it with convert and use it just like you did earlier.

Wrapping it up

With the commands you've learned in this post it should be easy enough to optimize and manipulate your images in the command line. For more examples check out the usage section on the Imagemagick website. I personally feel like using Imagemagick has improved my workflow and I hope it can (and will) do the same for you.

Getting started with Gulp

Let's talk about tools first

Lately I've noticed that many Front-end developers get caught up in tools. Should they use Less, or Sass? Do they code in Sublime or Atom? Or should they pick up Coda 2? What frameworks should they learn? Is Angular worth their time? Or maybe they should go all out on Ember or Backbone.

And then any developer will reach that point where they want to actually compile their css, concatenate their javascript and minify them all. So then there is the question, what do I use for that? Well, there's many options for that as well! Some prefer Grunt, others pick Gulp and some others turn to Codekit for this. Personally I got started with Codekit and swapped that out for Gulp later on. The reason I chose Gulp over Grunt? I liked the syntax better and people said it was exponentially faster than Grunt.

What is Gulp

After dropping all these tools in the previous paragraphs you might be confused. This article will focus on getting you started with Gulp. But what is Gulp exactly?

Gulp is a task runner, it's purpose is to perform repetitive tasks for you. When you are developing a website some things you might want to automate are:

  • Compiling css
  • Concatenate javascript files into a single file
  • Refresh your browser
  • Minify your css and javascript files

This would be a very basic setup. Some more advanced task include:

  • Running jshint
  • Generating an icon font
  • Using a cachebuster
  • Generating spritesheets

And many, many more. The way Gulp does all these things is through plugins. This makes Gulp a very small and lightweight utility that can be expanded with plugins so it does whatever you want. At this time there's about 1200 plugins available for gulp.

When should I learn Gulp

You should learn Gulp whenever you feel like you are ready for it. When you're starting out as a front-end developer you will have to learn so many things at once I don't think there's much use in immediately jumping in to use Sass, Gulp and all the other great tools that are available. If you feel like you want to learn Sass (or Less) as soon as you start learning css you don't have to learn Gulp as well. You could manually compile your css files as you go. Or you could use a graphical tool like Codekit for the time being. Like I said, there's no need to rush in and confuse yourself.

What about Grunt?

For those who payed attention, I mentioned Grunt at the start of this article. I don't use Grunt for a very simple reason, I don't like the syntax. And also, Gulp is supposed to be faster so that's nice. I feel like it's important to mention this because if you choose to use a tool like Gulp or Grunt you have to feel comfortable. A tool should help you get your job done better; using a tool shouldn't be a goal in itself.

That said, Grunt fulfills the same purpose as Gulp, which is running automated tasks. The way they do it is completely different though. Grunt uses a configuration file for it's tasks and then it runs all of the tasks in sequence. So it might take a Sass file and turn it into compiled css. After that it takes a css file and minifies it. Gulp uses javascript and streams. This means that you would take a Sass file and Gulp turns it into a so called stream. This stream then gets passed on an plugins modify it. You could compare this with an assembly line, you have some input, it get's modified n times and then at the end you get the output. In Gulp's case the output is a compiled and minified css file. Now, let's dive in and create our first gulpfile.js!

Creating a gulpfile

The gulpfile is your main file for running and using gulp. Let's create your first Gulp task!

Installing gulp

I'm going to assume you've already installed node and npm on your machine. If not go to the node.js website and follow the instructions over there. When you're done you can come back here to follow along.

To use gulp you need to install it on your machine globally and locally. Let's do the global install first:

npm install -g gulp

If this doesn't work at once you might have to use the sudo prefix to execute this command.

When this is done, you have successfully installed Gulp on your machine! Now let's do something with it.

Setting up a project

In this example we are going to use gulp for compiling sass to css. Create the following folders/files:

my_first_gulp/
    sass/
        style.scss
    css/
    gulpfile.js

In your style.scss files you could write the following contents:

$background-color: #b4da55

body {
    background-color: $background-color;
}

Allright, we have our setup complete. Let's set up Gulp for our project.

Setting up Gulp

Let's start by locally installing gulp for our project:

npm install gulp

If you're more familiar with npm and the package.json file that you can add to your project you'll want to run the command with --save-dev appended to it. That will add gulp as a dependency for your project. This also applies to any plugins you install.

Next up, we install the sass compiler:

npm install gulp-sass

We're all set to actually build our gulpfile now. Add the following code in there:

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('css', function(){
    gulp.src('sass/style.scss')
        .pipe(sass())
        .pipe(gulp.dest('css/'));
});

gulp.task('watch', function(){
    gulp.watch('sass/**/*.scss', ['css']);
});

In this file we import gulp and the gulp sass module. Then we define a task, we call the task css. Inside of this task we take our style.scss file and pipe it through to the sass plugin. What happens here is that the sass plugin modifies the stream that was created when we loaded sass/style.scss. When the sass plugin is done it sends the stream on to the next pipe call. This time we call gulp.dest to save the output of our stream to the css folder.

Think of this process as an assembly line for your files. You put the raw file in on one end, apply some plugins to it in order to build your final file and then at the end you save your output to a file.

The second task we define is called watch. This is the task we're going to start from the command line in a bit. What happens in this task is that we tell gulp to watch everything we have in our sass folder, as long as it ends in .scss. When something changes, Gulp will start the css task.

Go back to your command line and type:

gulp watch

Now go to your style.scss file, change something and save it (or just save it). You should see something happening in the command line now.

[20:54:17] Starting 'css'...
[20:54:17] Finished 'css' after 3.63 ms

That's the output I get. If you check the css folder, there should be a css file in there. You just generated that file! That's all there is to it.

Moving forward

Now that you've learned to compile sass files into css files with gulp you can start doing more advanced things. Gulps powerful syntax shouldn't make it too hard to expand on this example. Usually you just add an extra pipe to your file, call the plugin you want, repeat that a few times and then eventually you save the output file.

I hope this guide to getting started with gulp is helpful to you. If you have notes for me, questions or just want to chat you can send me a tweet @donnywals