最近はreactを使った開発が好きな、なおぴです。
reactを勉強しているとSPA開発をやってみたくなりますよね。
今回はMampを使いReact、TypeScript Laravelを連携するところまでやってみようと思います。
目次
バージョン
- React 18系
- Typescript 4系
- Laravel 8系
Laravelの開発環境構築
まずはバックエンドから開発をしていきます。
cd /Applications/MAMP/htdocs/
でhtdocsまで移動をします。その後以下のコマンドをターミナルで入力
ターミナルcomposer create-project laravel/laravel laravel-sns "8.*" --prefer-dist
作成した laravel-snsに移動して
php artisan serveで以下の画面が出たらOK。
DB設定
使用するDBはなんでもいいと思いますが今回はMampを使っているので
MySqlを使用します。Mampを開いてWebStartからphpMyAdminを開いて
データベースを作成後、ユーザを作っておいてください。
次に.envに設定してDB情報を記述して、php artisan migrateでmigrationが通ればOK。
React TypeScriptインストール
まずwebpack.mix.jsを書き換える必要があります。
webpack.mix.js
const mix = require("laravel-mix");
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel applications. By default, we are compiling the CSS
| file for the application as well as bundling up all the JS files.
|
*/
mix.ts("resources/ts/index.tsx", "public/js").sass(
"resources/sass/app.scss",
"public/css"
);
if (mix.inProduction()) {
mix.version();
}
その後ターミナルを開いて以下のコマンドを順番に入力してください。
ターミナルnpm install npm i -D react react-dom @types/react @types/react-dom npm install ts-loader typescript sass-loader@^12.1.0 sass resolve-url-loader@^5.0.0 --save-dev --legacy-peer-deps tsc --init --jsx react
次にresources/ts/index.tsx resources/sass/app.scssを作成してください。
その後index.tsxを最低限動くようにします
index.tsx
import React from "react";
import ReactDOM from "react-dom";
const App = () => {
return <h1>Laravel SPA</h1>;
};
ReactDOM.render(<App />, document.getElementById("app"));
変更したらターミナルでnpm run prodを入力。ビルドが完了したら
resources/views/welcome.blade.phpをindex.blade.phpに変更して以下のように記述
index.php
<!DOCTYPE html>
<html lang="ja"">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<link rel="stylesheet" href="{{mix('css/app.css')}}">
</head>
<body>
<div id="app"></div>
<script src="{{mix('js/index.js')}}"></script>
</body>
</html>
web.phpのルート変更も忘れずにしてください!
最後にサーバを立ち上げて以下の画面になれば完了です!