clock menu more-arrow no yes

Filed under:

Using BrowserSync and Gulp with the Rails Asset Pipeline

The Rails Asset Pipeline doesn't have to stand in the way of auto-reload on save workflow bliss!

Recently some coworkers on my team were inquiring in Slack about the possibility of enabling auto reloading on the app we're building to speed up CSS/HTML build-out. They've recently been doing design sprints and the lack of auto reload was a hindrance for speedy experimentation as they designed in browser.

My initial answer to the question was "not any time soon" but then I found a couple hours yesterday to play around and at the end of that time I had BrowserSync running via Gulp, working quite nicely with the limitations of the Asset Pipeline. Good job Winston on under promising and over delivering!

Just to backup, BrowserSync is a utility that makes developing across devices much more pleasant. At its most basic functionality, you can use it to automatically reload pages when you make changes to files, so if you're writing a bunch of HTML in your text editor, your updates appear in the browser upon saving. But it is even better if you're trying to monitor your changes across multiple browsers or devices; that's where the Sync part of its name comes in. If you have a page open in Chrome and also on a tablet, scrolling on one will scroll on the other as well. Clicking on an element will trigger a click on the same element in the other device. It's quite useful.

In the past, when I used BrowserSync I had it as part of a Gulp setup that handled all asset management; JS concatenation, Sass Compilation, minification, etc. In Rails, it is non-trivial to avoid using the Asset Pipeline so the simplest solution is to not avoid it. This isn't awful for BrowserSync, but it has meant until now that to update the CSS in the browser you needed to fully refresh the page which can take quite a few seconds on a large Rails app.

Yesterday while building the gulpfile for our app I saw a new to me addition to the reload() api in BrowserSync's documentation: the ability to pass in specific files or filetypes as an argument to reload to just have those files refreshed; saving an entire page reload. Since Rails handles file concatenation and sass compilation when the assets are trequested we can use this API to fake css injection without a full reload. Here's what my gulp tasks looked like:

You'll notice that for view files and JS files I call reload() with no arguments, but for Sass changes, I use a task that passes in *.css as an argument, ensuring all CSS files on the page are reloaded. So there you have it, using Gulp and BrowserSync to make local development on Rails that much nicer!