Vite 是一个现代化的前端构建工具,它提供极快的开发环境,并为生产环境打包你的代码。使用 Laravel 构建应用时,你通常会使用 Vite 将应用的 CSS 和 JavaScript 文件打包成生产就绪的资产。
Laravel 通过提供官方插件和 Blade 指令,与 Vite 无缝集成,以在开发和生产中加载你的资产。
[!NOTE]
以下文档讨论了如何手动安装和配置 Laravel Vite 插件。然而,Laravel 的 入门套件 已经包含了所有这些脚手架,并且是开始使用 Laravel 和 Vite 的最快方式。
您必须确保已安装 Node.js (16+) 和 NPM,然后才能运行 Vite 和 Laravel 插件:
node -v
npm -v您可以轻松地使用来自 Node 官方网站 的简单图形化安装程序,安装最新版本的 Node 和 NPM。或者,如果您正在使用 Laravel Sail,您可以通过 Sail 调用 Node 和 NPM:
./vendor/bin/sail node -v
./vendor/bin/sail npm -v在 Laravel 的全新安装中,你将找到一个 package.json 文件位于应用程序目录结构的根部。默认的 package.json 文件已经包含了开始使用 Vite 和 Laravel 插件所需的一切。你可以通过 NPM 安装应用程序的前端依赖:
npm installVite 通过项目根目录中的 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', // [tl! remove]
'resources/js/app.js',
]),
],
});而是,您应该通过 JavaScript 导入您的 CSS。通常,这将在您的应用程序的 resources/js/app.js 文件中完成:
import './bootstrap';
import '../css/app.css'; // [tl! add]Laravel 插件也支持多个入口点和高级配置选项,例如 SSR 入口点。
如果您的本地开发 Web 服务器通过 HTTPS 提供您的应用程序,您可能会遇到连接到 Vite 开发服务器的问题。
如果您正在使用 Laravel Herd 并已将站点安全化,或者您正在使用 Laravel Valet 并已针对您的应用程序运行了 secure 命令,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', // [tl! add]
}),
],
});当使用另一个 Web 服务器时,您应该生成一个受信任的证书,并手动配置 Vite 以使用生成的证书:
// ...
import fs from 'fs'; // [tl! add]
const host = 'my-app.test'; // [tl! add]
export default defineConfig({
// ...
server: { // [tl! add]
host, // [tl! add]
hmr: { host }, // [tl! add]
https: { // [tl! add]
key: fs.readFileSync(`/path/to/${host}.key`), // [tl! add]
cert: fs.readFileSync(`/path/to/${host}.crt`), // [tl! add]
}, // [tl! add]
}, // [tl! add]
});如果您无法为您的系统生成受信任的证书,您可以安装并配置 @vitejs/plugin-basic-ssl 插件。当使用不受信任的证书时,您将需要在浏览器中接受适用于 Vite 的开发服务器的证书警告通过遵循控制台中的“Local”链接在运行 npm run dev 命令时。
当在 Windows Subsystem for Linux 2 (WSL2) 上,在 Laravel Sail 中运行 Vite 开发服务器时,您应该将以下配置添加到您的 vite.config.js 文件中,以确保浏览器可以与开发服务器通信:
// ...
export default defineConfig({
// ...
server: { // [tl! add:start]
hmr: {
host: 'localhost',
},
}, // [tl! add:end]
});如果当开发服务器运行时,您的文件更改未在浏览器中反映,您可能还需要配置 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 客户端以启用热模块替换。在构建模式下,该指令将加载您已编译和版本化的资产,包括任何导入的 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 有两种方式。您可以通过 dev 命令运行开发服务器,这在本地开发时非常有用。开发服务器将自动检测您文件的更改,并立即在任何打开的浏览器窗口中反映这些更改。
或者, 运行 build 命令将对你的应用程序资源进行版本管理和打包, 并为将其部署到生产环境做好准备:
# Run the Vite development server...
npm run dev
# Build and version the assets for production...
npm run build如果您正在运行开发服务器在 Sail 在 WSL2 上,您可能需要一些 额外配置 选项。
默认情况下,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 框架构建前端,那么您还需要安装 @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,
},
},
}),
],
});[!NOTE]
Laravel 的 入门套件 已经包含了适当的 Laravel、Vue 和 Vite 配置。这些入门套件提供了使用 Laravel、Vue 和 Vite 上手的最快方式。
如果您想使用 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')@viteReactRefresh 指令必须在 @vite 指令之前调用。
[!NOTE]
Laravel 的 入门套件 已经包含了正确的 Laravel、React 和 Vite 配置。这些入门套件提供了最快的方式来开始使用 Laravel、React 和 Vite。
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 结合使用,我们建议配置 资产预取。
[!NOTE]
Laravel 的 入门套件 已经包含了适当的 Laravel、Inertia 和 Vite 配置。这些入门套件提供最快速的方式来开始使用 Laravel、Inertia 和 Vite。
在使用 Vite 并在应用的 HTML、CSS 或 JS 中引用资产时,有几个注意事项需要考虑。首先,如果您使用绝对路径引用资产,Vite 不会将该资产包含在构建中;因此,您应该确保该资产在您的公共目录中可用。在使用 专用 CSS 入口点 时,应避免使用绝对路径,因为在开发过程中,浏览器会尝试从托管 CSS 的 Vite 开发服务器加载这些路径,而不是从您的公共目录加载。
当引用相对资产路径时,你应该记住这些路径是相对于它们被引用的文件而言的。任何通过相对路径引用的资产都将由 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">[!NOTE]
Laravel 的 入门套件 已包含正确的 Tailwind 和 Vite 配置。或者,如果你想在不使用我们任何入门套件的情况下使用 Tailwind 和 Laravel,请查阅 Tailwind 的 Laravel 安装指南。
所有 Laravel 应用程序已包含 Tailwind 和一个配置正确的 vite.config.js 文件。因此,您只需启动 Vite 开发服务器或运行 dev Composer 命令,它将启动 Laravel 和 Vite 开发服务器:
composer run dev你的应用程序的CSS可以放在resources/css/app.css文件中。
当在你的 JavaScript 或 CSS 中引用资产时,Vite 会自动处理并进行版本控制。此外,在构建基于 Blade 的应用程序时,Vite 也可以处理并对你在 Blade 模板中单独引用的静态资产进行版本控制。
然而,为了实现这一点,你需要通过将静态资产导入到应用程序的入口点,让 Vite 识别你的资产。例如,如果你想处理并版本化存储在 resources/images 中的所有图像以及存储在 resources/fonts 中的所有字体,你应该在应用程序的 resources/js/app.js 入口点中添加以下内容:
import.meta.glob([
'../images/**',
'../fonts/**',
]);这些资源现在将由 Vite 处理,当运行 npm run build。然后你可以在 Blade 模板中使用 Vite::asset 方法,它将返回给定资源的带版本号的 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/**语言/**资源/语言/**resources/views/**路由/**监听 routes/** 目录很有用,如果您正在利用 Ziggy 在您的应用程序前端中生成路由链接。
如果这些默认路径不满足您的需求, 您可以指定您自己的路径列表以供监视:
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 资产的功能。
你可以指示 Laravel 预先加载你的资产 通过调用 Vite::prefetch 方法 在服务提供者的 boot 方法中:
<?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');
}鉴于上述代码,预取现在将在您手动分发 vite:prefetch 事件到 window 对象时开始。例如,您可以使预取在页面加载三秒后开始:
<script>
addEventListener('load', () => setTimeout(() => {
dispatchEvent(new Event('vite:prefetch'))
}, 3000))
</script>ASSET_URL 环境变量。
ASSET_URL=https://cdn.example.com配置资产 URL 后,所有重写到您资产的 URL 都将以配置的值作为前缀:
https://cdn.example.com/build/assets/app.9dce8d17.js请记住 绝对 URL 不会被 Vite 重写, 因此它们不会被添加前缀。
你可以通过在应用程序的 .env 文件中,为环境变量添加 VITE_ 前缀,将它们注入到你的 JavaScript 中:
VITE_SENTRY_DSN_PUBLIC=http://example.com你可以通过 import.meta.env 对象访问注入的环境变量:
import.meta.env.VITE_SENTRY_DSN_PUBLICLaravel 的 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// [tl! add:start]
{
parent::setUp();
$this->withoutVite();
}// [tl! add:end]
}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" // [tl! remove]
"build": "vite build && vite build --ssr" // [tl! add]
}然后,要构建并启动SSR服务器,您可以运行以下命令:
npm run build
node bootstrap/ssr/ssr.js如果你正在使用 与 Inertia 配合的 SSR,你可以改为使用 inertia:start-ssr Artisan 命令来启动 SSR 服务器:
php artisan inertia:start-ssr[!NOTE]
Laravel 的 入门套件 已经包含了正确的 Laravel、Inertia SSR 和 Vite 配置。这些入门套件提供了使用 Laravel、Inertia SSR 和 Vite 最快捷的方式。
如果您希望在您的 script 和 style 标签上包含一个 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);如果你的 Vite manifest 包含用于你的资产的 integrity 散列,Laravel 将自动将 integrity 属性添加到它生成的任何脚本和样式标签上,以强制执行 子资源完整性。默认情况下,Vite 不在其 manifest 中包含 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';// [tl! add]
export default defineConfig({
plugins: [
laravel({
// ...
}),
manifestSRI(),// [tl! add]
],
});如果需要,您也可以自定义存放完整性哈希值的清单键:
use Illuminate\Support\Facades\Vite;
Vite::useIntegrityKey('custom-integrity-key');如果您想完全禁用此自动检测,您可以将 false 传递给 useIntegrityKey 方法:
Vite::useIntegrityKey(false);如果你需要在你的脚本和样式标签上包含额外属性,例如 data-turbo-track 属性,你可以通过 useScriptTagAttributes 和 useStyleTagAttributes 方法指定它们。通常,这些方法应该从 服务提供者 调用:
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,
]);[!警告]
该$chunk和$manifest参数将为null当 Vite 开发服务器正在运行时。
开箱即用,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...
},
});如果你在浏览器中从 Vite 开发服务器获取资源时遇到跨域资源共享 (CORS) 问题,你可能需要授予你的自定义源对开发服务器的访问权限。Vite 结合 Laravel 插件允许以下源,无需任何额外配置:
::1127.0.0.1localhost*.test*.本地主机APP_URL 在 项目的 .env允许项目使用自定义来源最简单的方法是确保应用程序的 APP_URL 环境变量与您在浏览器中访问的来源匹配。例如,如果您访问的是 https://my-app.laravel,您应该更新您的 .env 以使其匹配:
APP_URL=https://my-app.laravel如果你需要对源进行更精细的控制,例如支持多个源,你应该利用Vite 全面灵活的内置 CORS 服务器配置。例如,你可以将多个源指定在server.cors.origin 配置选项中在项目的vite.config.js 文件中:
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
refresh: true,
}),
],
server: { // [tl! add]
cors: { // [tl! add]
origin: [ // [tl! add]
'https://backend.laravel', // [tl! add]
'http://admin.laravel:8566', // [tl! add]
], // [tl! add]
}, // [tl! add]
}, // [tl! add]
});您还可以包含正则表达式模式,这在您希望允许给定顶级域的所有来源时非常有用,例如 *.laravel:
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
refresh: true,
}),
],
server: { // [tl! add]
cors: { // [tl! add]
origin: [ // [tl! add]
// Supports: SCHEME://DOMAIN.laravel[:PORT] [tl! add]
/^https?:\/\/.*\.laravel(:\d+)?$/, //[tl! add]
], // [tl! add]
}, // [tl! add]
}, // [tl! add]
});某些 Vite 生态系统内的插件假定以斜杠开头的 URL 将始终指向 Vite 开发服务器。然而,由于 Laravel 集成的特性,情况并非如此。
举例来说,vite-imagetools 插件在Vite服务您的资产时输出如下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"><!-- [tl! remove] -->
+ <img src="http://[::1]:5173/@imagetools/f0b2f404b13f052c604e632f2fb60381bf61a520"><!-- [tl! add] -->