How to Add Vue to a Rails 5.1 App

  • rails, vue.js
  • 0 Comments

Rails 5.1 makes it really easy to use JavaScript libraries such as Vue. The latest version of Rails provides Yarn support so JS dependencies play nice with the assets pipeline. I haven't seen too many resources for creating a new Rails project with Vue, so here is how I did it.

  1. Update Rails with gem install rails -v 5.1
  2. I didn't have Node.js installed, so I had to install that next (you might not need to): https://nodejs.org/en/download/
  3. Install Yarn: https://yarnpkg.com/lang/en/docs/install/ . I used Homebrew. I had to update it first with brew update and then I was able to run brew install yarn
  4. Run rails new with the webpack vue flag: rails new my_app --webpack=vue .
  5. If you haven't already, run rails db:create and rails db:migrate and fire up Rails server to make sure everything is up and running.
  6. In the file structure, you'll notice a hello_vue.js file in app/javascript/packs. At the top of the file, there are commented-out instructions for adding <%= javascript_pack_tag 'hello_vue' %> to the <head> of app/views/layouts/application.html.erb. Do that now.
  7. Create a controller. I used rails g controller Teams and in the controller add an index action:
class TeamsController < ApplicationController
  def index
  end
end

Add routes:

Rails.application.routes.draw do
  resources :teams
end

In config/environments/development.rb, add config.x.webpacker[:dev_server_host] = "http://127.0.0.1:8080" This will enable javascript_pack_tag to load assets from the webpack dev server.

Run the webpack server on another port: ./bin/webpack-dev-server --host 127.0.0.1

Create index.html.erb in views/teams and navigate to http://localhost:3000/teams. If you see the "Hello Vue", you are good to go.