It's light, flexible, easy to learn and work both for creating small components like a full front-end app.
Today we gonna see how to integrate this framework in Rails with Webpacker.
Note that you can follow the same steps for any other framework : Angular, React, ...
Let's dive in.
First make sure that you have installed rails, nodeJS and npm, and let’s generate a new Rails app with webpacker.
Rails new hello_vuejs // into your Gemfile add the following line gem 'webpacker' // And install the dependencies bundle
Then let’s initialize webpacker. Within our rails app folder, execute the following lines :
rails g webpacker:install rails g webpacker:install:vuejs
This work well if you have an existing application, but for a brand new one, you can go faster with :
gem install webpacker rails new hello_vuejs --webpack=vue
What did webpacker created
- config/webpack contains configurations for webpacker
- environement configs
- extras loaders
- check webpacker documentation for more details
- note the packs folder, that’s where webpacker will be looking for creating your bundles
Finally you’ll find on the root of your rails app :
- babel.config.js - configuration for babel, a JS compiler
- package.json - package description for NPM
- postcss.config.js - configuration for webpacker postcss-loader
- yarn.lock - where yarn store what is installed
You’ll probably not have to touch any of those files.
So Webpacker is based on yarn, so you can use it to add extra dependencies. For example, if you want (you will) add vuex :
yarn add vuex
To run your rails app, you have to run in one terminal as usual :
And it’s better to run in another one :
One last thing to do before to start writting serious code business, the assets.
In your app/views/layouts/application.html.erb you have to make couple of changes :
We keep the stylesheet_link_tag as you may want to keep/load general styles from /app/assets/stylesheets/application.sass For instance, things like your bootstrap or other framework …
Finally, we have also a stylesheet_pack_tag. As the name suggest, it will also load a BUNDLE. This time, this one comes from VueJS specifities. Indeed, .vue files contain html, js code and styles.
Webpacker take care of packaging all of them into a .css pack as well for us.
What’s next ?
That’s it, happy coding.