跳到内容

资源打包 (Vite)

简介

Vite 是一个现代化的前端构建工具,它提供了极快的开发环境,并将您的代码打包以用于生产。在使用 Laravel 构建应用程序时,您通常会使用 Vite 将应用程序的 CSS 和 JavaScript 文件打包成可用于生产的资源。

Laravel 通过提供官方插件和 Blade 指令来无缝集成 Vite,从而在开发和生产环境中加载您的资源。

lightbulb

您正在运行 Laravel Mix 吗?Vite 已在新 Laravel 安装中取代 Laravel Mix。有关 Mix 的文档,请访问 Laravel Mix 网站。如果您想切换到 Vite,请参阅我们的 迁移指南

在 Vite 和 Laravel Mix 之间选择

在过渡到 Vite 之前,新的 Laravel 应用程序在打包资源时使用 Mix,它由 webpack 提供支持。Vite 专注于在构建丰富的 JavaScript 应用程序时提供更快、更高效的体验。如果您正在开发单页应用程序 (SPA),包括使用 Inertia 等工具开发的应用程序,Vite 将是完美的选择。

Vite 也适用于带有 JavaScript "sprinkles" 的传统服务器端渲染应用程序,包括使用 Livewire 的应用程序。但是,它缺少 Laravel Mix 支持的一些功能,例如将未在 JavaScript 应用程序中直接引用的任意资源复制到构建中的能力。

迁移回 Mix

您是否已使用我们的 Vite 脚手架启动了一个新的 Laravel 应用程序,但需要迁移回 Laravel Mix 和 webpack?没问题。请参阅我们的 官方指南,了解如何从 Vite 迁移到 Mix

安装与设置

lightbulb

以下文档讨论如何手动安装和配置 Laravel Vite 插件。但是,Laravel 的 入门套件 已经包含了所有这些脚手架,是开始使用 Laravel 和 Vite 的最快方法。

安装 Node

您必须确保在运行 Vite 和 Laravel 插件之前安装了 Node.js (16+) 和 NPM

node -v
npm -v

您可以使用 官方 Node 网站上的简单图形安装程序轻松安装最新版本的 Node 和 NPM。或者,如果您正在使用 Laravel Sail,则可以通过 Sail 调用 Node 和 NPM

./vendor/bin/sail node -v
./vendor/bin/sail npm -v

安装 Vite 和 Laravel 插件

在全新的 Laravel 安装中,您会在应用程序目录结构的根目录中找到一个 package.json 文件。默认的 package.json 文件已经包含了开始使用 Vite 和 Laravel 插件所需的一切。您可以通过 NPM 安装应用程序的前端依赖项

npm install

配置 Vite

Vite 通过项目根目录中的 vite.config.js 文件进行配置。您可以根据需要自由自定义此文件,并且还可以安装应用程序所需的任何其他插件,例如 @vitejs/plugin-vue@vitejs/plugin-react

Laravel Vite 插件要求您指定应用程序的入口点。这些可以是 JavaScript 或 CSS 文件,并且包括预处理语言,例如 TypeScript、JSX、TSX 和 Sass。

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
plugins: [
laravel([
'resources/css/app.css',
'resources/js/app.js',
]),
],
});

如果您正在构建 SPA,包括使用 Inertia 构建的应用程序,Vite 在没有 CSS 入口点的情况下效果最佳

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
plugins: [
laravel([
'resources/css/app.css',
'resources/js/app.js',
]),
],
});

相反,您应该通过 JavaScript 导入 CSS。通常,这会在您的应用程序的 resources/js/app.js 文件中完成

import './bootstrap';
import '../css/app.css';

Laravel 插件还支持多个入口点和高级配置选项,例如 SSR 入口点

使用安全开发服务器

如果您的本地开发 Web 服务器通过 HTTPS 为您的应用程序提供服务,您可能会遇到连接到 Vite 开发服务器的问题。

如果您正在使用 Laravel Herd 并已保护站点,或者您正在使用 Laravel Valet 并已针对您的应用程序运行了 安全命令,则 Laravel Vite 插件将自动检测并为您使用生成的 TLS 证书。

如果您使用与应用程序目录名称不匹配的主机保护了站点,则可以在应用程序的 vite.config.js 文件中手动指定主机

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
plugins: [
laravel({
// ...
detectTls: 'my-app.test',
}),
],
});

当使用另一个 Web 服务器时,您应该生成一个受信任的证书并手动配置 Vite 以使用生成的证书

// ...
import fs from 'fs';
 
const host = 'my-app.test';
 
export default defineConfig({
// ...
server: {
host,
hmr: { host },
https: {
key: fs.readFileSync(`/path/to/${host}.key`),
cert: fs.readFileSync(`/path/to/${host}.crt`),
},
},
});

如果您无法为系统生成受信任的证书,则可以安装和配置 @vitejs/plugin-basic-ssl 插件。当使用不受信任的证书时,您需要在浏览器中接受 Vite 开发服务器的证书警告,方法是在运行 npm run dev 命令时按照控制台中的“Local”链接操作。

在 WSL2 上的 Sail 中运行开发服务器

当在 Windows Subsystem for Linux 2 (WSL2) 上的 Laravel Sail 中运行 Vite 开发服务器时,您应该将以下配置添加到 vite.config.js 文件中,以确保浏览器可以与开发服务器通信

// ...
 
export default defineConfig({
// ...
server: {
hmr: {
host: 'localhost',
},
},
});

如果在开发服务器运行时,您的文件更改未反映在浏览器中,您可能还需要配置 Vite 的 server.watch.usePolling 选项

加载您的脚本和样式

配置好 Vite 入口点后,您现在可以在应用程序根模板的 <head> 中添加的 @vite() Blade 指令中引用它们

<!DOCTYPE html>
<head>
{{-- ... --}}
 
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

如果您通过 JavaScript 导入 CSS,则只需包含 JavaScript 入口点

<!DOCTYPE html>
<head>
{{-- ... --}}
 
@vite('resources/js/app.js')
</head>

@vite 指令将自动检测 Vite 开发服务器并注入 Vite 客户端以启用热模块替换 (HMR)。在构建模式下,该指令将加载您编译和版本化的资源,包括任何导入的 CSS。

如果需要,您还可以在调用 @vite 指令时指定编译后的资源的构建路径

<!doctype html>
<head>
{{-- Given build path is relative to public path. --}}
 
@vite('resources/js/app.js', 'vendor/courier/build')
</head>

内联资源

有时可能需要包含资源的原始内容,而不是链接到该资源的版本化 URL。例如,当将 HTML 内容传递给 PDF 生成器时,您可能需要将资源内容直接包含在页面中。您可以使用 Vite 门面提供的 content 方法输出 Vite 资源的内容

@use('Illuminate\Support\Facades\Vite')
 
<!doctype html>
<head>
{{-- ... --}}
 
<style>
{!! Vite::content('resources/css/app.css') !!}
</style>
<script>
{!! Vite::content('resources/js/app.js') !!}
</script>
</head>

运行 Vite

您可以通过两种方式运行 Vite。您可以通过 dev 命令运行开发服务器,这在本地开发时很有用。开发服务器将自动检测您文件的更改,并立即在任何打开的浏览器窗口中反映出来。

或者,运行 build 命令将对您应用程序的资源进行版本化和捆绑,使其准备好部署到生产环境

# Run the Vite development server...
npm run dev
 
# Build and version the assets for production...
npm run build

如果您在 WSL2 上的 Sail 中运行开发服务器,则可能需要一些额外的配置选项。

使用 JavaScript

别名

默认情况下,Laravel 插件提供了一个常用的别名,以帮助您快速上手并方便地导入应用程序的资源

{
'@' => '/resources/js'
}

您可以通过将自己的别名添加到 vite.config.js 配置文件中来覆盖 '@' 别名

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
plugins: [
laravel(['resources/ts/app.tsx']),
],
resolve: {
alias: {
'@': '/resources/ts',
},
},
});

Vue

如果您想使用 Vue 框架构建前端,那么您还需要安装 @vitejs/plugin-vue 插件

npm install --save-dev @vitejs/plugin-vue

然后,您可以将该插件包含在您的 vite.config.js 配置文件中。将 Vue 插件与 Laravel 一起使用时,您还需要一些额外的选项

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
 
export default defineConfig({
plugins: [
laravel(['resources/js/app.js']),
vue({
template: {
transformAssetUrls: {
// The Vue plugin will re-write asset URLs, when referenced
// in Single File Components, to point to the Laravel web
// server. Setting this to `null` allows the Laravel plugin
// to instead re-write asset URLs to point to the Vite
// server instead.
base: null,
 
// The Vue plugin will parse absolute URLs and treat them
// as absolute paths to files on disk. Setting this to
// `false` will leave absolute URLs un-touched so they can
// reference assets in the public directory as expected.
includeAbsolute: false,
},
},
}),
],
});
lightbulb

Laravel 的入门套件已经包含正确的 Laravel、Vue 和 Vite 配置。请查看 Laravel Breeze,以最快的方式开始使用 Laravel、Vue 和 Vite。

React

如果您想使用 React 框架构建前端,那么您还需要安装 @vitejs/plugin-react 插件

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(),
],
});

您需要确保任何包含 JSX 的文件都具有 .jsx.tsx 扩展名,并且在需要时更新您的入口点,如上面所示

您还需要在现有的 @vite 指令旁边包含额外的 @viteReactRefresh Blade 指令。

@viteReactRefresh
@vite('resources/js/app.jsx')

必须在 @vite 指令之前调用 @viteReactRefresh 指令。

lightbulb

Laravel 的入门套件已经包含正确的 Laravel、React 和 Vite 配置。请查看 Laravel Breeze,以最快的方式开始使用 Laravel、React 和 Vite。

Inertia

Laravel Vite 插件提供了一个方便的 resolvePageComponent 函数,以帮助您解析 Inertia 页面组件。下面是该助手在 Vue 3 中使用的示例;但是,您也可以在其他框架(如 React)中使用该函数

import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
 
createInertiaApp({
resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.mount(el)
},
});

如果您将 Vite 的代码拆分功能与 Inertia 一起使用,我们建议配置 资源预取

lightbulb

Laravel 的入门套件已经包含正确的 Laravel、Inertia 和 Vite 配置。请查看 Laravel Breeze,以最快的方式开始使用 Laravel、Inertia 和 Vite。

URL 处理

当使用 Vite 并在应用程序的 HTML、CSS 或 JS 中引用资源时,有几个注意事项需要考虑。首先,如果您使用绝对路径引用资源,Vite 将不会将该资源包含在构建中;因此,您应确保该资源在您的 public 目录中可用。当使用专用 CSS 入口点时,应避免使用绝对路径,因为在开发过程中,浏览器会尝试从 Vite 开发服务器(CSS 托管的位置)加载这些路径,而不是从您的 public 目录加载。

当引用相对资源路径时,您应该记住这些路径相对于它们所引用的文件。通过相对路径引用的任何资源都将被 Vite 重写、版本化和捆绑。

考虑以下项目结构

public/
taylor.png
resources/
js/
Pages/
Welcome.vue
images/
abigail.png

以下示例演示了 Vite 将如何处理相对和绝对 URL

<!-- This asset is not handled by Vite and will not be included in the build -->
<img src="/taylor.png">
 
<!-- This asset will be re-written, versioned, and bundled by Vite -->
<img src="../../images/abigail.png">

使用样式表

您可以在 Vite 文档中了解有关 Vite CSS 支持的更多信息。如果您正在使用 PostCSS 插件(如 Tailwind),您可以在项目的根目录中创建一个 postcss.config.js 文件,Vite 将自动应用它

export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
lightbulb

Laravel 的入门套件已经包含正确的 Tailwind、PostCSS 和 Vite 配置。或者,如果您想在不使用我们入门套件之一的情况下使用 Tailwind 和 Laravel,请查看 Tailwind 的 Laravel 安装指南

使用 Blade 和路由

使用 Vite 处理静态资源

当在 JavaScript 或 CSS 中引用资源时,Vite 会自动处理并对其进行版本控制。此外,当构建基于 Blade 的应用程序时,Vite 还可以处理和版本控制您仅在 Blade 模板中引用的静态资源。

但是,为了实现此目的,您需要通过将静态资源导入到应用程序的入口点来使 Vite 知道您的资源。例如,如果要处理和版本控制存储在 resources/images 中的所有图像和存储在 resources/fonts 中的所有字体,则应在应用程序的 resources/js/app.js 入口点中添加以下内容

import.meta.glob([
'../images/**',
'../fonts/**',
]);

现在,当运行 npm run build 时,Vite 将会处理这些资源。然后,您可以使用 Vite::asset 方法在 Blade 模板中引用这些资源,这将返回给定资源的版本化 URL

<img src="{{ Vite::asset('resources/images/logo.png') }}">

保存时刷新

当您的应用程序使用传统的服务器端渲染与 Blade 构建时,当您更改应用程序中的视图文件时,Vite 可以通过自动刷新浏览器来改进您的开发工作流程。要开始使用,您只需将 refresh 选项指定为 true 即可。

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
plugins: [
laravel({
// ...
refresh: true,
}),
],
});

refresh 选项为 true 时,在以下目录中保存文件将触发浏览器在您运行 npm run dev 时执行完整页面刷新

  • app/Livewire/**
  • app/View/Components/**
  • lang/**
  • resources/lang/**
  • resources/views/**
  • routes/**

如果您使用 Ziggy 在应用程序的前端生成路由链接,则监视 routes/** 目录很有用。

如果这些默认路径不符合您的需求,您可以指定您自己的监视路径列表

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
plugins: [
laravel({
// ...
refresh: ['resources/views/**'],
}),
],
});

在底层,Laravel Vite 插件使用 vite-plugin-full-reload 包,该包提供了一些高级配置选项来微调此功能的行为。如果您需要这种级别的自定义,您可以提供 config 定义

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
plugins: [
laravel({
// ...
refresh: [{
paths: ['path/to/watch/**'],
config: { delay: 300 }
}],
}),
],
});

别名

在 JavaScript 应用程序中,通常会创建别名以引用常用目录。但是,您也可以通过使用 Illuminate\Support\Facades\Vite 类上的 macro 方法在 Blade 中创建别名。“宏”通常应在服务提供程序boot 方法中定义

/**
* Bootstrap any application services.
*/
public function boot(): void
{
Vite::macro('image', fn (string $asset) => $this->asset("resources/images/{$asset}"));
}

定义宏后,可以在模板中调用它。例如,我们可以使用上面定义的 image 宏来引用位于 resources/images/logo.png 的资源

<img src="{{ Vite::image('logo.png') }}" alt="Laravel Logo">

资源预取

当使用 Vite 的代码拆分功能构建 SPA 时,会在每次页面导航时获取所需的资源。此行为可能会导致 UI 渲染延迟。如果这对于您选择的前端框架来说是一个问题,Laravel 提供了在初始页面加载时急切预取您的应用程序的 JavaScript 和 CSS 资源的功能。

您可以通过在服务提供程序boot 方法中调用 Vite::prefetch 方法来指示 Laravel 急切预取您的资源

<?php
 
namespace App\Providers;
 
use Illuminate\Support\Facades\Vite;
use Illuminate\Support\ServiceProvider;
 
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// ...
}
 
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Vite::prefetch(concurrency: 3);
}
}

在上面的示例中,资源将在每次页面加载时以最大 3 个并发下载预取。您可以修改并发性以适应您的应用程序的需求,或者如果应用程序应一次下载所有资源,则可以指定无并发限制

/**
* Bootstrap any application services.
*/
public function boot(): void
{
Vite::prefetch();
}

默认情况下,预取将在 页面加载事件触发时开始。如果您想自定义预取开始的时间,您可以指定 Vite 将侦听的事件

/**
* Bootstrap any application services.
*/
public function boot(): void
{
Vite::prefetch(event: 'vite:prefetch');
}

给定上面的代码,预取现在将在您在 window 对象上手动调度 vite:prefetch 事件时开始。例如,您可以在页面加载三秒后开始预取

<script>
addEventListener('load', () => setTimeout(() => {
dispatchEvent(new Event('vite:prefetch'))
}, 3000))
</script>

自定义基本 URL

如果您的 Vite 编译的资源部署到与您的应用程序不同的域(例如通过 CDN),您必须在应用程序的 .env 文件中指定 ASSET_URL 环境变量

ASSET_URL=https://cdn.example.com

配置资源 URL 后,所有重写的资源 URL 将以配置的值为前缀

https://cdn.example.com/build/assets/app.9dce8d17.js

请记住,绝对 URL 不会被 Vite 重写,因此它们不会带有前缀。

环境变量

您可以通过在应用程序的 .env 文件中为 JavaScript 环境变量添加 VITE_ 前缀来将其注入到 JavaScript 中

VITE_SENTRY_DSN_PUBLIC=http://example.com

您可以通过 import.meta.env 对象访问注入的环境变量

import.meta.env.VITE_SENTRY_DSN_PUBLIC

在测试中禁用 Vite

Laravel 的 Vite 集成将在运行测试时尝试解析您的资源,这需要您运行 Vite 开发服务器或构建您的资源。

如果您希望在测试期间模拟 Vite,您可以调用 withoutVite 方法,该方法可用于扩展 Laravel 的 TestCase 类的任何测试

test('without vite example', function () {
$this->withoutVite();
 
// ...
});
use Tests\TestCase;
 
class ExampleTest extends TestCase
{
public function test_without_vite_example(): void
{
$this->withoutVite();
 
// ...
}
}

如果您想为所有测试禁用 Vite,您可以从基本 TestCase 类上的 setUp 方法中调用 withoutVite 方法

<?php
 
namespace Tests;
 
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
 
abstract class TestCase extends BaseTestCase
{
protected function setUp(): void
{
parent::setUp();
 
$this->withoutVite();
}
}

服务器端渲染 (SSR)

Laravel Vite 插件可以轻松设置 Vite 的服务器端渲染。要开始使用,请在 resources/js/ssr.js 创建一个 SSR 入口点,并通过将配置选项传递给 Laravel 插件来指定该入口点

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
ssr: 'resources/js/ssr.js',
}),
],
});

为确保您不会忘记重建 SSR 入口点,我们建议在应用程序的 package.json 中增强 “build” 脚本以创建您的 SSR 构建

"scripts": {
"dev": "vite",
"build": "vite build"
"build": "vite build && vite build --ssr"
}

然后,要构建和启动 SSR 服务器,您可以运行以下命令

npm run build
node bootstrap/ssr/ssr.js

如果您使用 Inertia 的 SSR,您可以改为使用 inertia:start-ssr Artisan 命令来启动 SSR 服务器

php artisan inertia:start-ssr
lightbulb

Laravel 的入门套件已经包含正确的 Laravel、Inertia SSR 和 Vite 配置。请查看 Laravel Breeze,以最快的方式开始使用 Laravel、Inertia SSR 和 Vite。

脚本和样式标签属性

内容安全策略 (CSP) Nonce

如果您希望在脚本和样式标签上包含 nonce 属性,作为您的 内容安全策略的一部分,您可以使用自定义 中间件中的 useCspNonce 方法生成或指定 nonce

<?php
 
namespace App\Http\Middleware;
 
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Vite;
use Symfony\Component\HttpFoundation\Response;
 
class AddContentSecurityPolicyHeaders
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
Vite::useCspNonce();
 
return $next($request)->withHeaders([
'Content-Security-Policy' => "script-src 'nonce-".Vite::cspNonce()."'",
]);
}
}

调用 useCspNonce 方法后,Laravel 将自动在所有生成的脚本和样式标签上包含 nonce 属性。

如果您需要在其他地方指定 nonce,包括 Laravel 的入门套件中包含的 Ziggy @route 指令,您可以使用 cspNonce 方法检索它

@routes(nonce: Vite::cspNonce())

如果您已经有一个您希望 Laravel 使用的 nonce 值,您可以将该 nonce 值传递给 useCspNonce 方法。

Vite::useCspNonce($nonce);

子资源完整性 (SRI)

如果您的 Vite 清单文件包含了资源的 integrity 哈希值,Laravel 将会自动在它生成的任何 script 和 style 标签上添加 integrity 属性,以强制执行 子资源完整性(Subresource Integrity)。默认情况下,Vite 不会在其清单文件中包含 integrity 哈希值,但您可以通过安装 vite-plugin-manifest-sri NPM 插件来启用它。

npm install --save-dev vite-plugin-manifest-sri

然后,您可以在 vite.config.js 文件中启用此插件。

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import manifestSRI from 'vite-plugin-manifest-sri';
 
export default defineConfig({
plugins: [
laravel({
// ...
}),
manifestSRI(),
],
});

如果需要,您还可以自定义清单文件中用于查找完整性哈希值的键。

use Illuminate\Support\Facades\Vite;
 
Vite::useIntegrityKey('custom-integrity-key');

如果您想完全禁用此自动检测功能,可以将 false 传递给 useIntegrityKey 方法。

Vite::useIntegrityKey(false);

任意属性

如果您需要在 script 和 style 标签上包含其他属性,例如 data-turbo-track 属性,您可以通过 useScriptTagAttributesuseStyleTagAttributes 方法来指定它们。通常,这些方法应该从服务提供者中调用。

use Illuminate\Support\Facades\Vite;
 
Vite::useScriptTagAttributes([
'data-turbo-track' => 'reload', // Specify a value for the attribute...
'async' => true, // Specify an attribute without a value...
'integrity' => false, // Exclude an attribute that would otherwise be included...
]);
 
Vite::useStyleTagAttributes([
'data-turbo-track' => 'reload',
]);

如果您需要有条件地添加属性,可以传递一个回调函数,该回调函数将接收资源源路径、其 URL、其清单块以及整个清单。

use Illuminate\Support\Facades\Vite;
 
Vite::useScriptTagAttributes(fn (string $src, string $url, array|null $chunk, array|null $manifest) => [
'data-turbo-track' => $src === 'resources/js/app.js' ? 'reload' : false,
]);
 
Vite::useStyleTagAttributes(fn (string $src, string $url, array|null $chunk, array|null $manifest) => [
'data-turbo-track' => $chunk && $chunk['isEntry'] ? 'reload' : false,
]);
exclamation

当 Vite 开发服务器运行时,$chunk$manifest 参数将为 null

高级自定义

开箱即用,Laravel 的 Vite 插件使用了适用于大多数应用程序的合理约定;但是,有时您可能需要自定义 Vite 的行为。为了启用额外的自定义选项,我们提供了以下方法和选项,它们可以用来替代 @vite Blade 指令。

<!doctype html>
<head>
{{-- ... --}}
 
{{
Vite::useHotFile(storage_path('vite.hot')) // Customize the "hot" file...
->useBuildDirectory('bundle') // Customize the build directory...
->useManifestFilename('assets.json') // Customize the manifest filename...
->withEntryPoints(['resources/js/app.js']) // Specify the entry points...
->createAssetPathsUsing(function (string $path, ?bool $secure) { // Customize the backend path generation for built assets...
return "https://cdn.example.com/{$path}";
})
}}
</head>

vite.config.js 文件中,您应该指定相同的配置。

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
 
export default defineConfig({
plugins: [
laravel({
hotFile: 'storage/vite.hot', // Customize the "hot" file...
buildDirectory: 'bundle', // Customize the build directory...
input: ['resources/js/app.js'], // Specify the entry points...
}),
],
build: {
manifest: 'assets.json', // Customize the manifest filename...
},
});

更正开发服务器 URL

Vite 生态系统中的一些插件假设以正斜杠开头的 URL 将始终指向 Vite 开发服务器。然而,由于 Laravel 集成的性质,情况并非如此。

例如,当 Vite 为您的资源提供服务时,vite-imagetools 插件会输出如下所示的 URL:

<img src="/@imagetools/f0b2f404b13f052c604e632f2fb60381bf61a520">

vite-imagetools 插件期望输出的 URL 将被 Vite 拦截,然后插件可以处理所有以 /@imagetools 开头的 URL。如果您正在使用期望这种行为的插件,您将需要手动纠正 URL。您可以通过在 vite.config.js 文件中使用 transformOnServe 选项来实现此目的。

在这个特定的示例中,我们将开发服务器的 URL 前置到生成的代码中所有出现的 /@imagetools

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import { imagetools } from 'vite-imagetools';
 
export default defineConfig({
plugins: [
laravel({
// ...
transformOnServe: (code, devServerUrl) => code.replaceAll('/@imagetools', devServerUrl+'/@imagetools'),
}),
imagetools(),
],
});

现在,当 Vite 为资源提供服务时,它将输出指向 Vite 开发服务器的 URL。

- <img src="/@imagetools/f0b2f404b13f052c604e632f2fb60381bf61a520">
+ <img src="http://[::1]:5173/@imagetools/f0b2f404b13f052c604e632f2fb60381bf61a520">