Laravel Inertia React Tailwind 安裝教學
分類
說明
Laravel 前端安裝越來越複雜了,本篇將說明如何安裝 Inertia, React, Tailwind。
安裝 React
參考文章: https://react.dev/learn/add-react-to-an-existing-project
懶人包,在 Laravel 專案中安裝
npm install -D react react-dom
Inertia Server-side setup
參考文章: https://inertiajs.com/server-side-setup
安裝套件
composer require inertiajs/inertia-laravel
建立 Root template
resources/views/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.0, maximum-scale=1.0">
@viteReactRefresh
@vite('resources/js/app.jsx')
@inertiaHead
</head>
<body>
@inertia
</body>
</html>
注意我寫的是 app.jsx
,稍後會將 app.js
更名。
Middleware
安裝 Middleware
php artisan inertia:middleware
配置
bootstrap/app.php
use App\Http\Middleware\HandleInertiaRequests;
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
HandleInertiaRequests::class,
]);
})
Inertia Client-side setup
參考文章: https://inertiajs.com/client-side-setup
安裝套件
npm install -D @inertiajs/react
配置 app.js
將 app.js
改名成 app.jsx
resources/js/app.jsx
import './bootstrap';
import '../css/app.css';
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} />);
},
});
Vite 綁定 React
參考文章: https://laravel.com/docs/11.x/vite
安裝套件
npm install --save-dev @vitejs/plugin-react
配置
vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
laravel(['resources/js/app.jsx']),
react(),
],
});
安裝 Tailwind
參考文章: https://tailwindcss.com/docs/guides/laravel
安裝指令
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
配置
tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: [
'./resources/**/*.blade.php',
'./resources/**/*.js',
'./resources/**/*.jsx',
],
theme: {
extend: {},
},
plugins: [],
}
簡便版
使用 laravel installer 安裝 Breeze 起始套件,選擇 React, TypeScript,交由 Laravel 幫你把一切都安裝好。
composer global require laravel/installer
laravel new example-app
參考文章:
啟動
安裝完在本機啟動
# 安裝 npm
npm install
# 建置腳本
npm run build
# 啟動本機 server
composer run dev
參考
- https://inertiajs.com/server-side-setup
- https://laravel.com/docs/11.x
- https://laravel.com/docs/11.x/starter-kits
- https://laravel.com/docs/11.x/vite
- https://react.dev/learn/add-react-to-an-existing-project
- https://tailwindcss.com/docs/guides/laravel
- Laravel 11 with Inertia.Js and React.Js crash course in 2024 (NO Starter Kit) #1 Setup
一杯咖啡的力量,勝過千言萬語的感謝。
支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!