How to Integrate Vue.js with Rails 6

Bonfire Algorithm
The Startup
Published in
2 min readOct 21, 2019
Rails with a Vue. Photo by Austin Smart on Unsplash

Starting with Rails 6 the default JavaScript compiler is Webpacker (not Sprockets as before). Webpacker wraps the JavaScript build/bundling library Webpack (yes, the names are very similar and it does cause confusion).

With Rails 6 it’s pretty easy to integrate a JavaScript framework like Vue.js or React.

Simply start a new Rails project with the Webpack flag (exchange vue with react or a JS framework of your choice depending on what you like):

$ rails new hello_vue --webpack=vue

This will install a new project with Vue.js included as a pack. A pack is Rail’s terminology for any JavaScript we add to the project.

Open the file app/javascript/packs/hello_vue.js that Rails has generated for us. The file contains some JS code and instructions for how to integrate Vue.js with Rails.

First we comment out the first code snippet in the file, since we want to use Vue.js with the Webpacker compiler. At the bottom of the file we find the instructions for using Vue.js with Turbolinks. Rails comes with Turbolinks enabled, and this is the code we want, so we uncomment it. Also notice it says we should install vue-turbolinks:

$ yarn add vue-turbolinks

We then copy the following code from the file:

<div id='hello'>
{{message}}
<app></app>
</div>

And generate a controller and a view:

$ rails g controller Hello say_hello

We delete all the HTML in app/views/hello/say_hello.html.erb and replace it with the code we copied. We also add erb code to add the script. This could also be placed in the layout file, but since this is the only view using it, we put it here:

<%= javascript_pack_tag 'hello_vue' %><div id='hello'>
{{message}}
<app></app>
</div>

That should be it. But before we try it out, we’ll start a separate webpack server. We don’t need to do this, but it will make JS compile times much faster and also auto reload the page on JS change, so it is nice to have. Open a separate console, go into the project directory and type:

$ ./bin/webpack-dev-server

With the server started we fire up Rails:

$ rails s

And navigate to http://localhost:3000/hello/say_hello

You should see a “Hello Vue!” message.

--

--