VueJS with Webpack on Rails 4.2
by Gaurav Koley
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.
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?
Add the webpacker gem to your Gemfile as:
gem 'webpacker', github: 'rails/webpacker'
→ 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
<location of your ruby binary> is typically in
/home/<username>/.rvm/rubies/ruby-2.2.2/bin/ruby if you use rvm.
→ rake webpacker:install:vue
to install a webpack compatible vuejs project in the
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.
layouts/application.html.erb view to include the
application.js file from
And we are done!
Now while developing, run
To deploy, do nothing! Webpacker hooks up a new
webpacker:compile task to
assets:precompile, which gets run whenever you run
stylesheet_pack_tag helper method will automatically insert the correct HTML tag for compiled pack.
For further reading,