Search code examples
ruby-on-railsvue.jswebpacker

Connecting Front End and Backend - Rails and Vue


I am a little confused on this.
If in Rails, with erb files we can build pages layout, 1) in what situations would we use webpacker to add vue.

What i understand so far is a Vue application would at times make a request to the server lets say to populate data. 2) Would that be the only use or are they other uses cases?

Also 3) is it best to generate a vue or angular app as a standalone (like vue create app so vue is in a front end folder and rails in a backend folder) or to use webpacker in rails


Solution

  • I'll try and answer your three questions at once, hope that's ok!

    There are three common ways you can integrate Vue.js (or any JavaScript) library into a Rails application:

    • You can load it through sprockets, which is the built-in Rails asset packaging library. You would do this if your application is mostly going to be statically rendered and NOT a SPA (Single Paged Application). Sprockets is very tightly integrated with Rails, allowing you to refer to assets in your Rails templates and code. However, Sprockets is quite far behind Webpack in terms of the actual bundling/packaging, optimizations, and ease of use for any complex JS project. So you would only want to do this if you're adding a tiny amount of interactivity to a mostly static website.
    • You can load it through Webpacker. The idea of Webpacker is to give you a really easy way to start building a SPA with a rails backend. So you receive all the benefits of Webpack but don't need to tweek many configurations (at the start), or set up a separate web server, or worry about CORS. It's great for starting a new project/prototyping in or progressively integrating Vue.js into a larger static website. The downside is that Webpacker uses webpacker.yml for its default configuration which adds unnecessary confusion when you will eventually need to have more complex configs.
    • Finally you can load it through a separate web server ("standalone"), and in the long run, this will give you the greatest degree of freedom through less Webpacker middleware and access to the most updated webpack version. It also offers you the ability to scale, secure, and do fancy stuff like Server Side Rendering. The downside is this does require the most upfront setup and long-term maintenance time. AFAIK this is the most common way companies serve SPAs.