2024-05-27 渥太华微生活
使用 Inertia.js、React.js 和 Vite.js 设置 Laravel 应用:
1、创建应用程序
composer create-project laravel/laravel laravel-react-inertia
用下面命令运行本地服务器,检查网页看看 laravel 是否安装成功。
php artisan serve
2、服务器端设置 (Server-side setup)
1) 安装 Inertia.js 编译器依赖项:
composer require inertiajs/inertia-laravel
2) 将文件 resources/views/welcome.blade.php 重命名为 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"> <title>Laravel</title> @viteReactRefresh @vite(['resources/css/app.css', 'resources/js/app.jsx']) @inertiaHead </head> <body> @inertia </body> </html>
3) 生成 Inertia 中间件
php artisan inertia:middleware
4) 打开 bootstrap/app.php 文件,添加该中间件:
<?php use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; 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->append(HandleInertiaRequests::class); }) ->withExceptions(function (Exceptions $exceptions) { // })->create();
3、客户端设置 (Client-side setup)
1) 安装所有依赖项:
npm install @inertiajs/inertia-react @inertiajs/react @vitejs/plugin-react react react-dom
2) 更新 vite.config.js 文件:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [ laravel({ input: ['resources/css/app.css', 'resources/js/app.jsx'], refresh: true, }), react(), ], });
3) 将 resources/js/app.js 重命名为 app.jsx,并将以下代码粘贴到其中:
import React from 'react' import {createRoot} from 'react-dom/client' import {createInertiaApp } from '@inertiajs/inertia-react' import {resolvePageComponent} from 'laravel-vite-plugin/inertia-helpers' createInertiaApp({ resolve: (name) => resolvePageComponent(`./Pages/${name}.jsx`, import.meta.glob('./Pages/**/*.jsx')), setup({el, App, props}) { createRoot(el).render(<App {...props} />) }, });
4) 在 js 文件夹中创建一个“Pages”文件夹,并在该文件夹中创建一个名为“Test.jsx”的测试组件:
export default function Test() { return ( <h1>This is test component</h1> ) }
4、渲染组件
打开 routes/web.php,尝试在主页上渲染 Test.jsx:
<?php use Illuminate\Support\Facades\Route; use Inertia\Inertia; Route::get('/', function () { return Inertia::render('Test'); });
5、运行测试
在一个终端运行 VITE server
npm run dev
在另一个终端运行 Laravel server
php artisan serve
在浏览器中检查 http://127.0.0.1:8000 是否运行成功。
编者注:新闻取自各大新闻媒体,新闻内容并不代表本网立场!文字和图片来自网络,版权归原作者所有。如有侵权,请速联系小编,立即删除。
全部评论 (0) |
---|