ソフトウェアエンジニアの王子です。
オリンピックのカーリングを見すぎて、投げる前にどこを狙うかがわかるようになってきました。
コーナーガードは攻撃的な戦術です。
さて、前回の私の記事はこちらです。 aimstogeek.hatenablog.com
出来上がるプロダクトや記法の問題であればReact/Vueはどちらでも良いと思っています。
ですが、Vue3に対応したUIフレームワークや周辺ライブラリの充実度合いの状況などを考えるとあと1〜2年はReactの方が有用でしょうか。
そこで今回は前回のLaravel+Sail+Vite環境にReactを入れてみます。
dockerコンテナの準備
# curl -s https://laravel.build/react_test_blog | bash # cd react_test_blog # alias sail='[ -f sail ] && bash sail || bash vendor/bin/sail' # sail up -d
http://localhostへのアクセスにより初期画面が表示されます。
Vite環境の用意
前回同様Laravel-Viteというパッケージを利用します。 バージョンが上がり初期化方法がアップデートされています。
- 導入手順
# sail npx @preset/cli apply --debug laravel:vite --no-ssh
- package.jsonの修正
"scripts": { "dev": "vite --host", "build": "vite build", },
- Laravel用のconfigの用意
# sail php artisan vendor:publish --tag=vite-config
- react_test_blog/config/vite.phpの修正
'entrypoints' => [ 'ssr' => 'resources/scripts/ssr.ts', 'paths' => [ 'resources/scripts/Index.tsx', ], 'ignore' => '/\\.(d\\.ts|json)$/', ],
dev_server.ping_before_using_manifest => false (デフォルトはtrue)
※こちらを変更しないと、HMRのための変更を検知してくれない
- docker-compose.ymlの修正
ports: - '${APP_PORT:-80}:80' - '3000:3000'
- reactパッケージの導入
# sail npm install --save-dev react react-dom @types/react @types/react-dom @vitejs/plugin-react-refresh
- vite.config.tsの修正
import { defineConfig } from 'vite' import laravel from 'vite-plugin-laravel' import reactRefresh from '@vitejs/plugin-react-refresh'; export default defineConfig({ plugins: [ laravel(), reactRefresh() ], })
- react_test_blog/resources/views/welcome.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</title> @react @client @tag('Index') </head> <div id="index"></div> </body> </html>
- react_test_blog/resources/scripts/Index.tsxの作成
import * as React from 'react'; import * as ReactDom from 'react-dom'; const Index = () => { return ( <div> react test blog. </div> ); } ReactDom.render(<Index />, document.getElementById('index'));
- 一度再起動
# sail down # sail up -d # sail php artisan view:clear #キャッシュが残ってると@viteのディレクティブが動作しない
- ビルド
# sail npm run dev
動作確認
上記の手順を実施後、localhostにアクセスすると「react test blog」とだけ書かれたシンプルなページが表示されます。
ViteのHMRが正常に動作するかを確認するために Index.tsxの「react test blog」を「Hello world」などに書き換えてみてください。
ブラウザのリロードを行わずにコンポーネントの再描画が行われていれば環境の構築は成功です。
HMRを行わずに静的ビルドを確認する場合は
# sail npm run build
を実行した後にreact_test_blog/config/vite.phpの
- dev_server.enabledをfalse
- ping_before_using_manifestをtrue
のどちらかの対応で、localhostで確認できます。 ちょっとデプロイや作業がしづらいので、どう使うのが正しいのかは追い追い調査します。
最後に
最近はViteの速度と手軽さに満足し、環境構築で少し苦労しようともwebpackには決して戻るものかと推進活動に力を入れています。
Vite未経験の方は是非導入してみてください。
今回はここまで。
読んで頂き、ありがとうございました!
\\『真のユーザーファーストでマーケットを創造する』仲間を募集中です!! // 919.jp