1
2

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 + TypeScript

Posted at

はじめに

今回はTypeScirptベースのLaravel + React環境の作成方法をまとめたいと思います。

Laravel + React + TypeScript 環境設定

Laravel のセットアップ

terminal
composer create-project laravel/laravel laravel_react_project
cd laravel_react_project

必要なモジュールのインストール

terminal
npm i
npm i -D typescript \
    react @types/react \
    react-dom @types/react-dom \
    @vitejs/plugin-react \
    sass
npx tsc --init --jsx react-jsx

Vite の設定

terminal
mv vite.config.js vite.config.ts
vite.config.ts
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';

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

resources 以下の設定

terminal
rm -rf resources/css resources/js resources/views/welcome.blade.php
mkdir resources/scss resources/ts
touch resources/scss/app.scss resources/ts/index.tsx \
    resources/views/index.blade.php
resources/ts/index.tsx
import { createRoot } from 'react-dom/client';

const container = document.getElementById('app');
const root = createRoot(container!);

root.render(
    <div className="red">
        Laravel + React + TypeScript
    </div>
);
resources/scss/app.scss
.red {
    color: red;
}
index.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 Vite</title>
        @viteReactRefresh
        @vite(["resources/scss/app.scss", "resources/ts/index.tsx"])
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>

route の設定

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

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

起動テスト

terminal
npm run dev
terminal
php artisan serve

http://localhost:8000/ にアクセスすると以下のような画面が表示されれば成功です。

image.png

まとめ

今回は簡単に Laravel + React + TypeScript の環境を作成する方法をまとめました。この上にAPIのなどを生やして実際のSPAサイトなどを作成してみてください。

1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?