Frontend Fun with Rails 5.1 and Webpacker Jan 8 2018
Client side frameworks for more responsive web apps are en vogue, and have been for a number of years now. The frameworks themselves change in popularity - to begin with it was Backbone, then Ember and Angular - more recently, frameworks like Vue and React have become the most popular choices.
Let's take a look at just how easy it is in Rails 5.1 now to setup Vue.js and React. Make sure you have the latest version of Rails installed, and then we'll setup a new empty app:
rails new frontend-fun
You can also specify to use webpack as part of this command and skip the next couple of steps:
rails new frontend-fun --webpack
However, if you're looking to add this to an existing Rails app, these next two steps will allow you to add Webpacker ready to use.
Within the app, add the
webpacker gem to
Then run bundle from a terminal in the root directory of the project to install the gem:
At this point, we'll now have some additional commands available to us courtesy of the webpacker gem, to install frontend packages. We'll get things rolling with the initial command to prep our webpacker config:
With that done, we should probably setup a basic page for testing, so create a new controller
app/controllers/site_controller.rb, with the following Ruby code in it:
class SiteController < ApplicationController end
Then we'll create a template for our content, at
Finally, in our
config/routes.rb file, we'll add a reference for the root of our app to the new controller and action:
Rails.application.routes.draw do root "site#index" end
If you test our app now, you'll see the FrontendFun header. Last thing we now need to do is hook in our webpacker JS, with a reference from our layout template. In
app/views/layouts/application.html.erb, below the
Hello World from Webpacker
Webpacker - it's alive!
To install Vue.js, run the following commands:
bin/rails webpacker:install:vue bin/yarn install
This will install the Vue.js packages. We'll then hook up the Hello Vue pack that is setup by default, by modifying our
Reload our page, and you'll now see Hello Vue! in our page body, which is coming directly from Vue.js!
Now, in a production application, you're unlikely to want to use more than one frontend framework, unless you were transitioning from one to another. But, this is FrontendFun, so we're going to add React too!
By now, this should be fairly straightforward, we run:
bin/rails webpacker:install:react bin/yarn install
This will install the React packages now, and setup a base
HelloReact component similar to our
HelloVue. So we'll just need to modify our
Once more, reload our page, and behold - Hello Vue! and Hello React!.
Two frontend frameworks, setup very easily, co-existing in the same HTML page in our Rails app. The possibilities are practically endless!
From here, you can edit either