I had a friend show me a way to easily integrate CoffeeScript into Gulp, and I’m not looking back.
If you didn’t notice before, I use a modular approach to organizing my Gulp, so I have quite a few JS files to convert. Needless to say, I didn’t want to have to do it manually, so I found some tools to help automate.
I’ve been a huge Grunt fan for awhile now, and it wasn’t until recently that I started using an up and coming tool Gulp for my tasks.
Special thanks to Dan Tello over at Viget for his post that really inspired me to get into this.
With Gulp, it’s all about the stream, man. You use asyncronous node pipe methods to chain streams together. It’s really tricky to understand if you’re not familiar with this concept, and it took me awhile (I’m still only now just getting it as I type).
With Grunt, it’s all about configuration; with Gulp, it’s all about building your tasks dynamically. It only took me an hour or two to migrate an existing Gruntfile over to a gulpfile. Including a learning curve with a new framework, this isn’t too bad.
I won’t dive too deep into it today, but one problem I ran into was with actually getting the tasks to finish before I started another one. It seemed like a bug, until I realized what was happening:
Gulp was working so fast, one stream hadn’t finished in time for the other to occur.
A common use case for this is compiling CSS, then minifying it. Seems simple, right? With Grunt, you’d just stack the tasks together, and since Grunt runs them one at a time, you have no issues.
Just an FYI here, I’m following Dan’s model of modularizing my tasks into individual files, hence the alternate filenames in the task definitions below. If you’re going with a basic setup, these can all live in your gulpfile.
This doesn’t work as you expect. If you remove all CSS files from your project and run gulp build, you’ll end up with a compiled CSS file, but no minified version. However, if you run gulp build again, you’ll get your minified version, because the CSS file is already there.
Fortunately, gulp ships with an orchestrator that allows you to essentially specify dependencies that other tasks require. These dependencies are other Gulp task definitions that return a stream.
To specify one, just add an array after you task name, as with my cssmin task below, where I’ve added ['stylus'].
Now for the tricky part. See on line 33 where I’m returning the task itself? If you omit this line, the dependency is considered resolved and will never run. This line is super important and was confusing the hell out of me for quite awhile there, so I thought I’d share in case someone else ends up confused.
Ideally, I could split this task into two separate task definitions, but for this project that was good enough. I always want my vendor to be compiled, and though it rarely changes, with Gulp the compilation was so fast it was not even noticeable without it.
That’s all for today: make sure you return that stream!