Quick Tip: Easily create single page applications with Sprockets
September 01, 2012For a new side project, I needed an easier way to create (and serve) a Single Page Application. I was not going to have a server/api, so a rails application was a no-go. Since I was going to use Scss and Coffee-Script, and split the codebase into various files, using the CLI was not pratical. I really would love to have all the benefits of the assets pipeline, but was not willing to go full-circle and use Rails.
The solution I’ve came up was this: using Sprockets to serve the assets, and a simple Sinatra application to serve the only html file. You’ll need to have a Gemfile with something like this:
And the only server-side code you will need to use is this one:
Then you can start to add your javascript files on src/javascripts, and your stylesheets on src/stylesheets. This is the code I’ve used for my “index” view:
The files I’ve required do exist, but they are only manifest files. This is my src/javascripts/application.js:
And this is my src/stylesheets/application.css:
As you can see, I have only one call to load all stylesheets and only one call to load the javascripts. Sprockets takes care to join all files into one, and has support to minification, Sass, Coffeescript, just like you would expect if you were using Rails. And you don’t need to add a benemoth to your project just to use some niceties.