Heroku Gulp

I, like other JavaScript geeks out there, was really excited to try Gulp when it first came out. It uses pipes and streams which makes it automatically cool. I was never a big fan of Grunt because it wasn’t really clear to me the “right way” to set it up. It’s also a little too black box for my liking. If it didn’t work, it could be difficult to track down where or how it failed.

I’ve been maintaining a small site for a few years that I’ve recently converted from Express to hapi. One of the small pain points in the migration was Stylus support. Express has a Stylus “compiler” middleware function that dynamically compiles and caches requests for Stylus files. At the time, hapi did not have an equivalent plugin. So I set out to write a simple build script with Gulp.

I’m not really going to go into how to write a Gulp file here. There are many articles out there by better writers than I that explain it better. So for the sake of brevity, here is my complete “gulpfile.js” and let’s move getting everything working on Heroku.

My first thought was to just check in and deploy the generated files since that is easier. I don’t like that approach because it makes change sets appear much larger than they really are. Those generated files will change and be overwritten constantly, but those changes aren’t important; the changes to the source files are. With that rulled out, the only other option was to have Gulp run after the code has been deployed.

Reading through the documentation, I learned about the `postinstall` npm hook Heroku provides. It’s purpose is to provide a way to run some build scripts after deployment. Sound familiar? We want to run a Gulp task after our site has been deployed.

One quick caveat to this method: Heroku runs `npm install —production` which does not install anything listed in `devDependencies` from the “package.json” file. That means that “gulp” and all of the required plugins, need to be listed under `dependencies`for this to work.

Finally, update your “package.json” file to look like this

“scripts”: { 
“start”: “node app”,
“postinstall”: “gulp default”

After successfully deploying your Node application to Heroku, the Node build back will run `npm run postinstall` which will run the “postinstall” script from the “package.json” file. That will run the locally installed copy of Gulp and start the Gulp task named “default”. If you’re looking at my Gulp file, that compiles Stylus and compresses my JavaScript.

After the `push` to Heroku, you can run `heroku logs —tail` to check in on the Gulp task and make sure it finishes.

Show your support

Clapping shows how much you appreciated Adam Bretz’s story.