레일즈의 Vue3

29893 단어 railsvuevue3webdev
버전:

레일 6
뷰 3

머리말



직장에서 ZAGE 까지 프로젝트 The Life Company 의 프론트엔드를 수행합니다. 애플리케이션은 Rails로 작성되었습니다. 합류하면서 프론트엔드의 일부에 Vue를 추가하고 싶었습니다. 그러나 Vue 3을 Rails에 추가하는 방법에 대한 튜토리얼을 찾을 수 없었습니다. 그래서 제가 찾고 있던 튜토리얼을 작성했습니다.

마지막에 알아야 할 것



이 문서에서는 Ruby on Rails 앱에 Vue 3를 설치하는 방법을 설명합니다. 결국 ERB 보기 템플릿 내에서 Vue 앱을 구현할 수 있어야 합니다. 이 튜토리얼의 코드는 내 Github Repositoryrails-vue3-app 에서 찾을 수 있습니다.

콘텐츠:
  • Introduction

  • Create Rails app
  • Setup Rails app
  • Install yarn

  • Install Vue3 & Co.

  • Configure Webpack environment
  • Set an alias
  • Vue Loader
  • Include .vue files
  • Set Vue properties


  • Create Vue app
  • Create entry point and SFC
  • Create Home controller and view as root route
  • Connect Vue and Rails

  • Next Steps

  • 소개

    Evan You released the Vue 3 2020년 9월. 이 기사는 Composition API와 같은 새로운 기능에 초점을 맞추거나 Vue2에서 Vue3으로 마이그레이션하는 방법을 설명하거나 설명하지 않습니다. official documentationmigration guide을 확인하십시오.

    Vue CLI와 Vite는 새로운 Vue 프로젝트를 쉽게 구성할 수 있는 훌륭한 도구이지만 현재 리소스에는 기존 코드베이스에 Vue3를 설치하는 방법에 대한 정보가 부족합니다. Rails 5+ 전체 스택 애플리케이션이 있는 경우 이미 webpacker 구성이 있을 가능성이 큽니다. 이 기사를 작성하는 현재 Webpacker는 rails webpacker:install:vue를 통해 Vue 2에 대한 스켈레톤을 제공하지만 Vue 3에는 아직 제공하지 않습니다. PR을 열어 상태를 확인했습니다here. 이제 Vue3를 기술 스택에 추가하는 방법에 대해 알아보겠습니다.

    Rails 앱 생성(선택 사항)

    레일 앱 설정

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

    rails new rails_vue3_app --webpack
    

    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.

    원사 설치

    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/
    

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

    npm i -g yarn
    cd rails_vue3_app
    yarn 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
    


    설치된 버전을 보려면 package.json를 확인하십시오. 최소 버전은 다음과 같아야 합니다.

    // ##############################
    // 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"
        // ...
      }
      // ...
    }
    


    웹팩 환경 구성

    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
    

    별칭 설정(선택 사항)

    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
    

    뷰 로더 추가

    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
    

    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'
        }]
    }
    
    // ##############################
    // 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
    

    .vue 파일 포함

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

    // ##############################
    // config/webpacker.yml
    // ##############################
    
    default: &default
      # ...
    
    
      extensions:
        # ...
        - .vue
    

    Vue 속성 설정

    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

    // ##############################
    // 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
    


    뷰 앱 만들기

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

    진입점 및 SFC 생성

    As explained above, I'd like to collect all Vue related code in a single directory. Therefore, create the folder Bundler Build Feature Flags in your root directory. In there, create the file ./app/javascript/src . 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 main.js . In there, create the file ./app/javascript/src/components . You can name the file also HelloWorld.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>
    

    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 hello-world.vue 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')
        })
    }
    

    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 main.js . But what, we haven't written this element yet. So let's do that now.

    홈 컨트롤러 생성 및 루트 경로로 보기

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

    rails generate controller Home index 
    

    Next, set the home controller as base route in .erb :

    # -----------------
    # config/routes.rb
    # -----------------
    
    # Rails.application.routes.draw do
    #   get 'home/index'
    
      root to: 'home#index'
    # end
    

    Vue와 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 config/routes.rb . Add or replace the dummy content with the following line:

    <!-- app/views/home/index.html -->
    
    <div id='vue-app'></div>
    

    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
    
    Open a browser and go to localhost:3000 . 모든 것이 작동하면 아무 것도 표시되지 않습니다(단, 제거하지 않은 경우 더미 HTML 코드). DOM을 검사할 때 idapp/views/home/index.html가 있는 빈div container이 있어야 합니다. 이 모든 것을 하나로 모으기 위한 마지막 단계는 Vue 애플리케이션의 진입점을 가져오는 것입니다.

    간단하게 유지하기 위해 이 자습서에서는 진입점을 vue-app에 직접 추가합니다. 물론 단일 팩을 만들 수도 있습니다. webpack(er)의 분할 청크 기능을 사용할 수도 있습니다. 하지만 지금은 application.js 항목을 열고 진입점을 가져오겠습니다.

    // ##############################
    // app/javascript/packs/application.js
    // ##############################
    
    // require("@rails/ujs").start()
    // require("turbolinks").start()
    // require("@rails/activestorage").start()
    // require("channels")
    import initVueApp from "@/main.js"
    
    initVueApp()
    


    페이지를 새로고침하면 "Hello World"가 표시됩니다! 잠시동안 이것저것 가지고 놀아보세요. 스타일을 변경하고, 메시지를 변경하고, 템플릿을 변경하십시오. 더 이상 Vue3에 단일 루트 요소가 필요하지 않다는 것을 잊지 마십시오. 따라서 div 컨테이너 또는 이와 유사한 래핑이 없습니다.

    다음 단계

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

    • pass properties from Rails to Vue
    • configure Linters

    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 Unsplash

    좋은 웹페이지 즐겨찾기