[Laravel] Laravel8에다가 React와 vue 올리기 (laravel/ui)

2021. 4. 5. 15:27· PHP/Laravel
목차
  1. 1. React.js
  2. 2. Vue.js

라라벨 프로젝트 내에서 리액트나, 뷰의 컴포넌트를 사용하는 방식입니다.
우선 공통으로 프론트엔드 스캐폴딩을 해주는 패키지인  laravel/ui 설치합니다.

composer require laravel/ui

 

1. React.js

 아래 명령어를 통해 React를 프로젝트 내에 추가합니다.

php artisan ui react

그러면 다음과 같은 명령어를 하라고 권할 겁니다.

npm install && npm run dev

windows에 vagrant로 vm 위에서 홈스테드를 돌리고 있다면 에러가 발생할 수 있습니다.

윈도우의 vagrant는 보안 문제로 symlink을 막아뒀기 때문인데,

해결하려면 vagrant를 관리자로 접속 후 Shared-Folders-Enable-Symlinks-create을 활성화시키면 됩니다.


윈도우에서 yarn install 하고 vagrant에서 npm run dev를 하는 방식으로 우회했습니다.

도커는 해당 이슈가 없다고 하던데 빨리 도커로 갈아타야죠

resources/js/components 폴더에 Example.js가 아래 코드와 같이 생성됩니다.
특정 아이디에 React Dom 통해 컴포넌트를 랜더링하는 방식입니다.

import React from 'react';
import ReactDOM from 'react-dom';

function Example() {
    return (
        <div className="container">
            <div className="row justify-content-center">
                <div className="col-md-8">
                    <div className="card">
                        <div className="card-header">Example Component</div>

                        <div className="card-body">I'm an example component!</div>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Example;

if (document.getElementById('example')) {
    ReactDOM.render(<Example />, document.getElementById('example'));
}

또한 resources/js/app.js에 다음과 같은 줄이 추가될 것입니다.

require('./components/Example');

vendor/laravel/ui/src/Presets/react-stubs/webpack.mix.js에서 아래와 같이 빌드하기 때문에 앞으로 추가되는 컴포넌트는 위와 같이 require로 app.js에 추가해야 합니다.

const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js')
    .react()
    .sass('resources/sass/app.scss', 'public/css');

welcome.balde를 아래와 같이 수정합니다.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="example"></div>
    <script src="{{asset('js/app.js')}}" defer></script>
</body>
</html>
npm run dev

컴포넌트를 수정했으니 이전과 같이 npm run dev을 통해 라라벨 mix로 빌드할 수 있지만,
매번 컴포넌트 수정사항이 있을 때마다 빌드하는 건 귀찮습니다.

 

아래 명령어로 수정 시 자동 컴파일을 하게 할 수 있습니다.

 npm run watch

위 명령어가 안 되는 세팅이 존재합니다, 그럴 때는 -poll 옵션을 추가하면 됩니다. 

 npm run watch-poll

 

이제 사이트 접속 시 아래와 같이 나오면 성공입니다. (저는 내용을 Hello World로 수정했습니다.)

 

2. Vue.js

아래 명령어로 뷰를 추가합니다.

php artisan ui vue

그러면 리액트 때와 마찬가지로 resources/js/components 폴더에 생기지만
이번에는 파일명이 ExampleComponent.vue입니다.

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        I'm an example component.
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>

뷰도 마찬가지로 앞으로 추가되는 컴포넌트는 app.js에 컴포넌트를 등록해야 합니다.

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue').default;

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
});

welcome.blade.php를 아래와 같이 수정합니다.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id='app'>
        <example-component></example-component>
    </div>
    <script src="{{asset('js/app.js')}}" defer></script>
</body>
</html>

dev 또는 watch를 통해 빌드를 해줍니다

npm run dev
 npm run watch

아래와 같은 화면이 나오면 성공

※ React와 Laravel 서버를 분리한 후 데이터가 필요할시 Laravel에 API 요청을 보내는 방법도 있지만 굳이 그렇게 할 필요는 없죠 ※

반응형

'PHP > Laravel' 카테고리의 다른 글

[Laravel] 테스트 개념 및 실행  (0) 2021.06.08
[Laravel] OAuth 2.0, Passport 개념  (0) 2021.04.06
[Laravel] 컴포넌트 총정리  (0) 2021.04.03
[LifeCycle] 라라벨 Kernel, Service provider  (0) 2021.03.03
[LifeCycle] 라라벨 Public/index.php  (0) 2021.03.03
  1. 1. React.js
  2. 2. Vue.js
'PHP/Laravel' 카테고리의 다른 글
  • [Laravel] 테스트 개념 및 실행
  • [Laravel] OAuth 2.0, Passport 개념
  • [Laravel] 컴포넌트 총정리
  • [LifeCycle] 라라벨 Kernel, Service provider
DSeung
DSeung
DSeung
Dev log
DSeung
  • 분류 전체보기 (193)
    • PHP (62)
      • Laravel (31)
      • Error (5)
      • Setting (11)
      • Modern PHP (15)
    • Go Lang (51)
      • Study (30)
      • Algorithm (17)
      • Setting (1)
      • Error (3)
    • Java (11)
      • Spring (3)
      • JSP (0)
      • Error (2)
      • Setting (2)
      • 단축키 (2)
    • JavaScript (6)
      • Modern JavaScript (4)
      • Node (1)
    • Android Kotlin (5)
      • Study (4)
      • Error (1)
    • 컴퓨팅 기술 (12)
      • 데이터베이스시스템 (4)
      • Docker (2)
      • 크롤링 & 스크래핑 (1)
      • API (1)
      • 클라우드 (1)
      • 네트워크 (1)
    • MySQL (7)
    • AWS (1)
    • Git (5)
      • GItLab (1)
      • GitHub (4)
    • 도메인 (2)
      • 안과 (2)
    • 자격증 (7)
      • SQLD (1)
      • 정보처리기사 (6)
    • Mac os (1)
    • 나머지 (13)
      • tistory (1)
      • 기타 (9)
      • 일기 (3)
    • 독서 (10)

인기 글

최근 글

블로그 메뉴

  • 홈
  • 태그
전체
오늘
어제
hELLO · Designed By 정상우.v4.2.0
DSeung
[Laravel] Laravel8에다가 React와 vue 올리기 (laravel/ui)
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.