VueJS with Webpack on Rails 4.2
by Gaurav Koley
VueJS is a snazzy new frontend Javascript Framework that helps build reactive User Interfaces. I have been following VueJS since its beta and have recently been using it extensively for my projects.
I use VueJS with Ruby on Rails. So far this was done by writing the Vue components as individual erb
partials and then include them in the UI as shown below. VueJS would compile the components and inject them as necessary at the client side.
<%= render 'shares/_shares_component' %>
<div id="shares_row">
<shares apiurl="<%= root_url%>shares/<%= @market_name %>.json" market="<%= @market_name %>"></shares>
</div>
<script type="text/javascript">
var nasdaq = new Vue({
el: '#shares_row'
});
</script>
This approach works when you don’t have many components and don’t have components being composed of other components themselves. That is where things start to get messy.
The VueJS community recommends use of webpack to create and manage large scale Vue projects. This requires a nodejs runtime and the ability to inject transpiled and minified JS into the layouts/application.html.erb
view. So how do I connect webpack with Rails?
Enter, Webpacker.
Add the webpacker gem to your Gemfile as: gem 'webpacker', github: 'rails/webpacker'
and run bundle install
.
Then run
→ rake webpacker:install
If you get an error like /usr/bin/env: ‘ruby2.2’: No such file or directory
Solve it by:
→ sudo update-alternatives --install /usr/bin/ruby2.2 ruby2.2 <location of your ruby binary> 1
Here <location of your ruby binary>
is typically in /home/<username>/.rvm/rubies/ruby-2.2.2/bin/ruby
if you use rvm.
Then, run
→ rake webpacker:install:vue
to install a webpack compatible vuejs project in the app/javascripts/packs/
folder. This also creates a package.json
file in the rails root directory as well as a config/webpack/
folder containing the webpack configuration for the VueJS project. The configuration works out of the box and you don’t really need to make any changes here.
Next, add <%= javascript_pack_tag 'application' %>
in your layouts/application.html.erb
view to include the application.js
file from app/javascripts/packs/
.
And we are done!
Now while developing, run ./bin/webpack-dev-server
alongside rails serve
.
To deploy, do nothing! Webpacker hooks up a new webpacker:compile
task to assets:precompile
, which gets run whenever you run assets:precompile
. The javascript_pack_tag
and stylesheet_pack_tag
helper method will automatically insert the correct HTML tag for compiled pack.
For further reading,