DEV Community

Cover image for Vue3 on Rails
Vannsl
Vannsl

Posted on • Updated on

Vue3 on Rails


Versions:

Rails 6
Vue 3


Foreword

At work, I do the frontend for the project ZAGE by The Life Company. The application is written in Rails. As I joined, I wanted to add Vue for some parts of the Frontend. But I couldn't find any tutorial on how to add Vue 3 to Rails. So, I wrote that tutorial, I was looking for.

What you should know at the end

This article explains how to install Vue 3 in a Ruby on Rails app. In the end, you should be able to implement a Vue app within an ERB view template. The code of this tutorial can be found in my Github Repository rails-vue3-app.

Content:

  1. Introduction
  2. Create Rails app
  3. Install Vue3 & Co.
  4. Configure Webpack environment
  5. Create Vue app
  6. Next Steps

Introduction

Evan You released the Vue 3 in September 2020. This article does neither focus on the new features like the Composition API nor explain nor explain how to migrate from Vue2 to Vue3. Check out the official documentation and migration guide for that.

While the Vue CLI and Vite are great tools to configure new Vue projects easily, current resources lack information on how to install Vue3 in existing codebases. When you have a Rails 5+ full-stack application, you most likely already have a webpacker configuration. As of the date I'm writing this article, Webpacker offers a skeleton for Vue 2 via rails webpacker:install:vue, but not for Vue 3 yet. I opened a PR, check the state here. So, let's dive right into how to add Vue3 into your tech stack.

Create Rails app (optional)

Setup rails app

To test the setup before adding it to your "real" codebase, you can create a new rails app.

rails new rails_vue3_app --webpack
Enter fullscreen mode Exit fullscreen mode

I'm not a rails developer, so feel free to give me tips and hints, if there are other best practices for rails specific code and commands.

Install yarn

If the output of the previous command says something like:

Yarn not installed. Please download and install Yarn from https://yarnpkg.com/lang/en/docs/install/
Enter fullscreen mode Exit fullscreen mode

...you need to install yarn and install the packages afterward.

npm i -g yarn
cd rails_vue3_app
yarn install
Enter fullscreen mode Exit fullscreen mode

Install Vue3 & Co.

If you run your rails app inside of Docker, you don't need to install anything on your host machine. You can install the packages within your docker container.

To use Vue3, you'll need (guess what :) ) Vue in version 3, Vue-Loader in version 16 beta, and the SFC compiler.

Vue3 is released on npm with the tag next. The current version is still 2.6.x to prevent developers from having to migrate to Vue3 if they don't want to. The same applies to the vue-loader.

# in rails_vue3_app
yarn add vue@next vue-loader@next @vue/compiler-sfc
Enter fullscreen mode Exit fullscreen mode

Check the package.json to see the installed versions. The minimal versions should be:

// ##############################
// package.json
// ##############################
{
  "name": "rails_vue_app",
  "private": true,
  "dependencies": {
    "@vue/compiler-sfc": "^3.0.0",
    "vue": "^3.0.0",
    "vue-loader": "^16.0.0-beta.8"
    // ...
  }
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Webpack environment configuration

Next, we need to tell Webpack what to do with *.vue files. For that, go to the file webpack/environment.js

By default, it should look like this:

// ##############################
// webpack/environment.js
// ##############################
const { environment } = require('@rails/webpacker')

module.exports = environment
Enter fullscreen mode Exit fullscreen mode

Set an alias (optional)

I like to put my Vue applications into a separate folder. I also want to use a Webpack alias for an easier path handling when importing files. I did that with the following configuration:

// ##############################
// webpack/environment.js
// ##############################
// const { environment } = require('@rails/webpacker')
const path = require("path")

const customConfig = {
  resolve:{
    alias: {
      "@": path.resolve(__dirname, "..", "..", "app/javascript/src")
    }
  }
}

environment.config.merge(customConfig)

// module.exports = environment
Enter fullscreen mode Exit fullscreen mode

Add Vue Loader

Now it's time to add the loader. It tells Webpack what to do with files that match to the Regex .vue.

// ##############################
// webpack/environment.js
// ##############################

// const { environment } = require('@rails/webpacker')
// const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')

// const customConfig = {
//   resolve:{
//     alias: {
//      '@': path.resolve(__dirname, '..', '..', 'app/javascript/src')
//     }
//   }
// }

// environment.config.merge(customConfig)

environment.plugins.prepend(
    'VueLoaderPlugin',
    new VueLoaderPlugin()
)

environment.loaders.prepend('vue', {
    test: /\.vue$/,
    use: [{
        loader: 'vue-loader'
    }]
})

// module.exports = environment
Enter fullscreen mode Exit fullscreen mode

Because I like to keep the file webpack/environment.js as clean and readable as possible, I outsourced the configuration of Vue in an own file within the folder webpack/loaders. By default it does not exist, so create it first using the terminal or your IDE. The end result should look like this:

// ##############################
// webpack/loaders/vue.js
// ##############################

module.exports = {
    test: /\.vue$/,
    use: [{
        loader: 'vue-loader'
    }]
}
Enter fullscreen mode Exit fullscreen mode
// ##############################
// webpack/environment.js
// ##############################

// const { environment } = require('@rails/webpacker')
// const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')
const vue = require('./loaders/vue');

// const customConfig = {
//   resolve:{
//     alias: {
//       '@': path.resolve(__dirname, '..', '..', 'app/javascript/src')
//     }
//   }
// }

// environment.config.merge(customConfig)

environment.plugins.prepend(
    'VueLoaderPlugin',
    new VueLoaderPlugin()
)

environment.loaders.prepend('vue', vue)

// module.exports = environment
Enter fullscreen mode Exit fullscreen mode

Include .vue files

Next, open the file config/webpacker.yml and add .vue to the extensions:

// ##############################
// config/webpacker.yml
// ##############################

default: &default
  # ...


  extensions:
    # ...
    - .vue
Enter fullscreen mode Exit fullscreen mode

Set Vue properties

It is strongly recommended to properly configure some properties of Vue in order to get proper tree-shaking in the final bundle. You can find more information in Vue3's README under Bundler Build Feature Flags.

// ##############################
// webpack/environment.js
// ##############################

// const { environment } = require('@rails/webpacker')
// const path = require('path')
const { DefinePlugin } = require('webpack')
// const { VueLoaderPlugin } = require('vue-loader')
// const vue = require("./loaders/vue");

// const customConfig = {
//   resolve:{
//     alias: {
//       "@": path.resolve(__dirname, "..", "..", "app/javascript/src")
//     }
//   }
// }

// environment.config.merge(customConfig)

// environment.plugins.prepend(
//     'VueLoaderPlugin',
//     new VueLoaderPlugin()
// )

environment.plugins.prepend(
    'Define',
    new DefinePlugin({
        __VUE_OPTIONS_API__: false,
        // or __VUE_OPTIONS_API__: true,
        __VUE_PROD_DEVTOOLS__: false
    })
)

// environment.loaders.prepend('vue', vue)

// module.exports = environment
Enter fullscreen mode Exit fullscreen mode

Create a Vue app

Everything should now be correctly set up. It's finally time to add our first Single File Component and load it into a container.

Create entry point and SFC

As explained above, I'd like to collect all Vue related code in a single directory. Therefore, create the folder ./app/javascript/src in your root directory. In there, create the file main.js. It will be the entry point for the Vue application. Leave it empty as it is, we'll come back to it again.

Next, let's create a Vue component. I propose to create the folder ./app/javascript/src/components. In there, create the file HelloWorld.vue. You can name the file also hello-world.vue if you prefer that syntax. Insert the following code:

// ##############################
// app/javascript/src/components/HelloWorld.vue
// ##############################

<template>
  <p>
    {{ message }}
  </p>
</template>

<script>
import { ref } from 'vue'

export default {
  name: 'HelloWorld',
  setup() {
      const message = ref('Hello World')

      return {
        message
      }
  }
}
</script>

<style scoped>
p {
  font-size: 2em;
  text-align: center;
}
</style>
Enter fullscreen mode Exit fullscreen mode

Of course you can write sassy CSS. Therefore add the lang attribute lang='scss' to the <script> section.

Now, let's head back to our main.js file and create the Vue app:

// ##############################
// app/javascript/src/main.js
// ##############################

import { createApp } from 'vue'
import HelloWorld from '@/components/HelloWorld.vue'

export default () => {
    document.addEventListener('DOMContentLoaded', () => {
        const app = createApp(HelloWorld)
        app.mount('#vue-app')
    })
}
Enter fullscreen mode Exit fullscreen mode

Okay, let's recap what has happened. We created an SFC (Single File Component). We created a Vue instance and mounted it into an HTML element with the id vue-app. But what, we haven't written this element yet. So let's do that now.

Create Home controller and view as root route

For that, let's create a HomeController with a view. Alternatively, you can go directly to the .erb file you want to add the Vue app to.

rails generate controller Home index 
Enter fullscreen mode Exit fullscreen mode

Next, set the home controller as base route in config/routes.rb:

# -----------------
# config/routes.rb
# -----------------

# Rails.application.routes.draw do
#   get 'home/index'

  root to: 'home#index'
# end
Enter fullscreen mode Exit fullscreen mode

Connect Vue and Rails

Finally, our configuration is done. Now we have a home page. We want to load the Vue app directly in this file. Head to app/views/home/index.html. Add or replace the dummy content with the following line:

<!-- app/views/home/index.html -->

<div id='vue-app'></div>
Enter fullscreen mode Exit fullscreen mode

Let's check out what's going on in the browser. Open your terminal and start the rails and the Webpack server with:

# in one tab
rails server

# in another tab
./bin/webpack-dev-server
Enter fullscreen mode Exit fullscreen mode

Open a browser and go to localhost:3000. If everything works, you should see nothing (but the dummy HTML code if you haven't removed it). When inspecting the DOM, there should be the empty div container with the id vue-app. Our last step to bring it all together is to import the entry point of our Vue application.

To keep it simple, we will add the entry point directly to the application.js in this tutorial. Of course, you can create a single pack for it. You can also use the split chunks feature of webpack(er). But for now, let's open app/javascript/packs/application.js and import our entry point:

// ##############################
// app/javascript/packs/application.js
// ##############################

// require("@rails/ujs").start()
// require("turbolinks").start()
// require("@rails/activestorage").start()
// require("channels")
import initVueApp from "@/main.js"

initVueApp()
Enter fullscreen mode Exit fullscreen mode

Reload the page, you should see "Hello World" now! Have fun playing around with it for a while. Change the style, change the message, change the template. Don't forget, that you don't need to have a single root element in Vue3 anymore. Therefore no wrapping div container or similar.

Next Steps

Congratulations, you have just installed Vue3 in a Rails app. Next, we will talk about how to:

Follow me to receive notifications, when I post those articles. I will link them here at the bottom of this article as soon as they're published.


Photo by Christian Holzinger on Unsplash

Top comments (7)

Collapse
 
phaedryx profile image
Tad Thorley • Edited

Thank you for this article. It is hard to find any materials on Vue 3 + Rails.

Question: wouldn't you want to put configuration like __VUE_PROD_DEVTOOLS__: false in production.js and __VUE_PROD_DEVTOOLS__: true in development.js?

Collapse
 
vannsl profile image
Vannsl

AFAIK the devtools should work on development (webpack mode / NODE_ENV "development") with that property set in environment.js.

Collapse
 
phaedryx profile image
Tad Thorley • Edited

I'm trying to follow this guide, but to mount Vue apps to existing HTML. I keep getting the error

Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js"
Enter fullscreen mode Exit fullscreen mode

It seems like this should work:

const customConfig = {
  resolve: {
    alias: {
      ...
      vue: 'vue/dist/vue.esm-bundler.js'
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

but I still get the same error. Has anyone encountered this? Where have I gone wrong?

Collapse
 
sanchezdav profile image
David Sanchez

OMG! This is an awesome post! ๐Ÿ™Œ Thanks for sharing! I'm a Rails developer and I was trying to configure Vue 3 in an application ๐Ÿ”ฅ

Collapse
 
niuage profile image
Robin Boutros

Thanks for the post, that was a great starting point. Keep the articles coming!

Collapse
 
ugifractal profile image
sugiarto

thanks

Some comments may only be visible to logged-in visitors. Sign in to view all comments.