Laravel11 + React + Inertia + Vite【Breeze無し】環境構築

こちらのサイトを参考にしました。

プロジェクト作成

composer create-project laravel/laravel react-inertia-app

// プロジェクトの中に入っておいてください
cd react-inertia-app

サーバーサイドのセットアップ

Inertia.jsの依存関係をインストール

composer require inertiajs/inertia-laravel

ファイル作成

resources/views/app.blade.php を作成し、以下のコードを記述してください。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
        @viteReactRefresh 
        @vite(['resources/css/app.css', 'resources/js/app.jsx'])
        @inertiaHead
    </head>
    <body>
        @inertia
    </body>
</html>

ミドルウェアの作成

以下のコマンドでミドルウェアを作成します。

php artisan inertia:middleware

そして、bootstrap/app.php に以下を追加してください。

(参考:公式サイト

use App\Http\Middleware\HandleInertiaRequests; // 追加

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [           // 追加
            HandleInertiaRequests::class,    // 追加
        ]);                                  // 追加
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

クライアントサイドのセットアップ

依存関係をインストール

npm install @inertiajs/inertia-react @inertiajs/react @vitejs/plugin-react react react-dom

Viteの設定

vite.config.js ファイルに以下を追加してください。

import { defineConfig } from "vite";
import laravel from "laravel-vite-plugin";
import react from "@vitejs/plugin-react";  // 追加

export default defineConfig({
    plugins: [
        react(),  // 追加
        laravel({
            input: ["resources/css/app.css", "resources/js/app.js"],
            refresh: true,
        }),
    ],
});

ファイル名変更とコードを追加

resources/js/app.jsapp.jsx に変更しておいてください。

そして、以下の記述を追加してください。

(参考:公式サイト

import "./bootstrap";
// 以下を追加
import { createInertiaApp } from "@inertiajs/react";
import { createRoot } from "react-dom/client";

createInertiaApp({
    resolve: (name) => {
        const pages = import.meta.glob("./Pages/**/*.jsx", { eager: true });
        return pages[`./Pages/${name}.jsx`];
    },
    setup({ el, App, props }) {
        createRoot(el).render(<App {...props} />);
    },
});

コンポーネントファイルを作成

resources/js/Pages/Test.jsx を作成し、以下のコードを記述してください。

import React, { useState } from "react";

const Test = () => {
    return <h1>This is test component</h1>;
};

export default Test;

ルーティング

routes/web.php に以下を追加してください。

use Inertia\Inertia;

Route::get('/', function () {
    return Inertia::render('Test');
});

動作確認

以下のコマンドを叩き、http://127.0.0.1:8000/で「This is test component」と表示されると成功です!

php artisan serve
npm run dev

コメント

タイトルとURLをコピーしました