1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

Laravel+Reactの技術と触れるために勉強用プロジェクトを作成しました。その備忘録として作成します。

開発環境

PHP: 8.3.8
Laravel: 11.13.0
react: 18.3.1
types/react: 18.3.3

Laravelのインストール

bash
composer create-project laravel/laravel laravel-react
cd laravel-react

以下のコードを実行すると画面が表示されます。

bash
php artisan serve

スクリーンショット 2024-06-22 182941.png

viteのインストール

Laravel9以降のバージョンでは、フロントエンド(JS,CSS)のビルドツールが、従来のLaravel MixからViteへと置き換わりました。そのため今回はviteのインストールをスキップします。Laravel Mixやほかのビルドツールを使用する場合は適宜調べてください。

React+vite+TypeScript+scssをインストール

今回使用するもろもろをインストールします。

bash
npm install react react-dom react-router-dom typescript @types/react @types/react-dom
npm install -D @vitejs/plugin-react sass
npm i -D react-router-dom @types/react-router-dom
npx tsc --init --jsx react-jsx

以下のコマンドを実行すると画像が表示されます。

bash
npm run dev

スクリーンショット 2024-06-22 182329.png

フロント側を作成

vite.config.jsファイルをvite.config.tsに名前変更してください。

ファイル名変更
vite.config.js → vite.config.ts

vite.config.tsの内容を以下に修正してください。

vite.config.ts
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/ts/App.tsx'],
            refresh: true,
        }),
    ],
});

resources/views/app.blade.phpを新規作成します。

app.blade.php
 <!DOCTYPE html>
 <html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

 <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">

     <title>laravel+React</title>
     @viteReactRefresh
     @vite(['resources/css/app.css', 'resources/ts/App.tsx'])
 </head>

 <body>
     <div id="app"></div>
 </body>

 </html>

resources/ts/App.tsxを新規作成します。

App.tsx
import React from 'react'
import { createRoot } from 'react-dom/client'

const App: React.FC = () => {
    return (
        <React.StrictMode>
            <p>Hello React !</p>
        </React.StrictMode>
    );
};

const appElement = document.getElementById('app') as HTMLElement
if (appElement) {
    const root = createRoot(appElement);
    root.render(<App />)
}

routes/web.phpに以下を追加します。

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

Route::get('{any}', function () {
    return view('app');
})->where('any', '.*');

画面をリロードして以下のような画面がでれば完了です。

スクリーンショット 2024-06-29 195954.png

おわりに

今回はLaravel+Reactを組み合わせたプロジェクトを作成しました。ここからコンポーネント作成、scss作成、Laravelとのapi連携など、やることはまだまだあります。この記事が開発の足掛かりとなっていただければ幸いです。

参考記事

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?