现状
-
SEO
-
webpack编译慢
-
页面加载慢,白屏时间长
ssr实现
技术方案
Inertia + Vue3 + Vite
- Inertiajs
构建单页应用程序,无需构建 API。
使用经典的服务器端路由创建现代单页 React、Vue等应用程序。适用于任何后端 — 针对 Laravel 进行了调整。
1、数据共享
public function share(Request $request): array
{
return array_merge(parent::share($request), [
//
"user"=> Auth::user() ? Auth::user()->only('id') : null,
]);
}
import { usePage } from '@inertiajs/vue3';
const page = usePage();
const user = page.props.user
- Vite
极速的服务启动
轻量快速的热重载
难点一:Vite集成
Laravel8.x不支持vite,需要手动配置;Laravel默认使用mix,配置方便,但是使用webpack,开发阶段编译较慢;
难点二:多语言处理
Inertia提供了一个中间件,所有的请求都会经过中间件,因此可以在这里设置服务端的多语言配置:
app()->setLocale(Cookie::get('lang', 'en'));
难点三:服务部署
@env(['local'])
<script type="module" src="http://localhost:5173/@vite/client"></script>
<link rel="stylesheet" href="http://localhost:5173/resources/css/app.css">
<script type="module" src="http://localhost:5173/resources/js/app.js"></script>
@endenv
@env(['production'])
<link rel="stylesheet" href="{{mix('css/pc.css')}}"/>
<script src="{{mix('js/pc.js')}}" defer></script>
@endenv
mix.copy(['public/build/assets/*.js'], 'public/js/pc.js');
mix.styles(['public/build/assets/*.css'], 'public/css/pc.css');
开发体验
- vite
VITE v4.5.0 ready in 595 ms
- mix
// 启动
Compiled Successfully in 4052ms
// 热更新
Compiled Successfully in 760ms
生产部署
- webpack
Compiled Successfully in 5396ms
- vite
✓ built in 3.55s
✓ built in 1.26s