PHP/Laravel

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

DSeung 2021. 4. 5. 15:27

라라벨 프로젝트 내에서 리액트나, 뷰의 컴포넌트를 사용하는 방식입니다.
우선 공통으로 프론트엔드 스캐폴딩을 해주는 패키지인  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 요청을 보내는 방법도 있지만 굳이 그렇게 할 필요는 없죠 ※

반응형