跳轉至內容

資源打包 (Vite)

簡介

Vite 是一款現代前端構建工具,它提供了極快的開發環境,並將您的程式碼打包以供生產使用。在構建 Laravel 應用程式時,您通常會使用 Vite 將應用程式的 CSS 和 JavaScript 檔案打包成生產環境就緒的資源。

Laravel 透過提供官方外掛和 Blade 指令,實現與 Vite 的無縫整合,從而載入用於開發和生產環境的資源。

安裝與設定

以下文件介紹瞭如何手動安裝和配置 Laravel Vite 外掛。不過,Laravel 的 入門套件 (Starter Kits) 已經包含了所有這些基礎架構,是開始使用 Laravel 和 Vite 最快捷的方式。

安裝 Node

在執行 Vite 和 Laravel 外掛之前,您必須確保已安裝 Node.js (16+) 和 NPM。

1node -v
2npm -v

您可以直接從 Node 官網 下載圖形化安裝程式,輕鬆安裝最新版本的 Node 和 NPM。或者,如果您正在使用 Laravel Sail,則可以透過 Sail 呼叫 Node 和 NPM。

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

安裝 Vite 和 Laravel 外掛

在全新的 Laravel 安裝中,您會在應用程式目錄結構的根目錄下找到一個 package.json 檔案。預設的 package.json 檔案已經包含了使用 Vite 和 Laravel 外掛所需的一切。您可以透過 NPM 安裝應用程式的前端依賴項:

1npm install

配置 Vite

Vite 透過專案根目錄下的 vite.config.js 檔案進行配置。您可以根據需要自定義此檔案,也可以安裝應用程式所需的任何其他外掛,例如 @vitejs/plugin-react@sveltejs/vite-plugin-svelte@vitejs/plugin-vue

Laravel Vite 外掛要求您指定應用程式的入口點。這些可以是 JavaScript 或 CSS 檔案,也包含預處理語言,如 TypeScript、JSX、TSX 和 Sass。

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel([
7 'resources/css/app.css',
8 'resources/js/app.js',
9 ]),
10 ],
11});

如果您正在構建 SPA(單頁應用,包括使用 Inertia 構建的應用),Vite 在沒有 CSS 入口點的情況下效果最好。

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel([
7 'resources/css/app.css',
8 'resources/js/app.js',
9 ]),
10 ],
11});

相反,您應該透過 JavaScript 匯入您的 CSS。通常,這會在應用程式的 resources/js/app.js 檔案中完成。

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

Laravel 外掛還支援多個入口點和高階配置選項,例如 SSR 入口點

使用安全的開發伺服器

如果您的本地開發 Web 伺服器透過 HTTPS 提供服務,您在連線 Vite 開發伺服器時可能會遇到問題。

如果您正在使用 Laravel Herd 並已保護了站點,或者您正在使用 Laravel Valet 並已對您的應用程式運行了 secure 命令,Laravel Vite 外掛將自動檢測併為您使用生成的 TLS 證書。

如果您使用不匹配應用程式目錄名稱的主機保護了站點,則可以在應用程式的 vite.config.js 檔案中手動指定主機。

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel({
7 // ...
8 detectTls: 'my-app.test',
9 }),
10 ],
11});

使用其他 Web 伺服器時,您應該生成一個受信任的證書,並手動配置 Vite 以使用該生成的證書。

1// ...
2import fs from 'fs';
3 
4const host = 'my-app.test';
5 
6export default defineConfig({
7 // ...
8 server: {
9 host,
10 hmr: { host },
11 https: {
12 key: fs.readFileSync(`/path/to/${host}.key`),
13 cert: fs.readFileSync(`/path/to/${host}.crt`),
14 },
15 },
16});

如果您無法為系統生成受信任的證書,可以安裝並配置 @vitejs/plugin-basic-ssl 外掛。當使用不受信任的證書時,您需要在執行 npm run dev 命令時,透過控制檯中的“Local”連結在瀏覽器中接受 Vite 開發伺服器的證書警告。

在 WSL2 的 Sail 中執行開發伺服器

當在 Windows Linux 子系統 2 (WSL2) 的 Laravel Sail 中執行 Vite 開發伺服器時,您應該將以下配置新增到 vite.config.js 檔案中,以確保瀏覽器能夠與開發伺服器通訊:

1// ...
2 
3export default defineConfig({
4 // ...
5 server: {
6 hmr: {
7 host: 'localhost',
8 },
9 },
10});

如果開發伺服器執行時檔案更改未反映在瀏覽器中,您可能還需要配置 Vite 的 server.watch.usePolling 選項

載入指令碼和樣式

配置好 Vite 入口點後,您現在可以在應用程式根模板的 <head> 中新增 @vite() Blade 指令來引用它們:

1<!DOCTYPE html>
2<head>
3 {{-- ... --}}
4 
5 @vite(['resources/css/app.css', 'resources/js/app.js'])
6</head>

如果您是透過 JavaScript 匯入 CSS,則只需要包含 JavaScript 入口點。

1<!DOCTYPE html>
2<head>
3 {{-- ... --}}
4 
5 @vite('resources/js/app.js')
6</head>

@vite 指令將自動檢測 Vite 開發伺服器並注入 Vite 客戶端以啟用熱模組替換 (HMR)。在構建模式下,該指令將載入已編譯和版本化的資源,包括任何已匯入的 CSS。

如果需要,您也可以在呼叫 @vite 指令時指定已編譯資源的構建路徑:

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

內聯資源 (Inline Assets)

有時可能需要包含資源的原始內容,而不是連結到資源的版本化 URL。例如,當向 PDF 生成器傳遞 HTML 內容時,可能需要直接在頁面中包含資源內容。您可以使用 Vite facade 提供的 content 方法輸出 Vite 資源的內容:

1@use('Illuminate\Support\Facades\Vite')
2 
3<!doctype html>
4<head>
5 {{-- ... --}}
6 
7 <style>
8 {!! Vite::content('resources/css/app.css') !!}
9 </style>
10 <script>
11 {!! Vite::content('resources/js/app.js') !!}
12 </script>
13</head>

執行 Vite

執行 Vite 有兩種方式。您可以透過 dev 命令執行開發伺服器,這在本地開發時非常有用。開發伺服器會自動檢測檔案更改,並立即反映在任何開啟的瀏覽器視窗中。

或者,執行 build 命令將對應用程式的資源進行版本控制和打包,併為部署到生產環境做好準備。

1# Run the Vite development server...
2npm run dev
3 
4# Build and version the assets for production...
5npm run build

如果您在 WSL2 的 Sail 中執行開發伺服器,可能需要一些 額外的配置 選項。

使用 JavaScript

別名 (Aliases)

預設情況下,Laravel 外掛提供了一個通用的別名,以幫助您快速上手並方便地匯入應用程式資源:

1{
2 '@' => '/resources/js'
3}

您可以將自己的別名新增到 vite.config.js 配置檔案中,從而覆蓋 '@' 別名:

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel(['resources/ts/app.tsx']),
7 ],
8 resolve: {
9 alias: {
10 '@': '/resources/ts',
11 },
12 },
13});

Vue

如果您想使用 Vue 框架構建前端,那麼您還需要安裝 @vitejs/plugin-vue 外掛:

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

然後,您可以將該外掛包含在 vite.config.js 配置檔案中。在 Laravel 中使用 Vue 外掛時,還有一些額外的選項需要注意。

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3import vue from '@vitejs/plugin-vue';
4 
5export default defineConfig({
6 plugins: [
7 laravel(['resources/js/app.js']),
8 vue({
9 template: {
10 transformAssetUrls: {
11 // The Vue plugin will re-write asset URLs, when referenced
12 // in Single File Components, to point to the Laravel web
13 // server. Setting this to `null` allows the Laravel plugin
14 // to instead re-write asset URLs to point to the Vite
15 // server instead.
16 base: null,
17 
18 // The Vue plugin will parse absolute URLs and treat them
19 // as absolute paths to files on disk. Setting this to
20 // `false` will leave absolute URLs un-touched so they can
21 // reference assets in the public directory as expected.
22 includeAbsolute: false,
23 },
24 },
25 }),
26 ],
27});

Laravel 的 入門套件 已經包含了正確的 Laravel、Vue 和 Vite 配置。這些入門套件是開始使用 Laravel、Vue 和 Vite 最快捷的方式。

React

如果您想使用 React 框架構建前端,那麼您還需要安裝 @vitejs/plugin-react 外掛:

1npm install --save-dev @vitejs/plugin-react

然後,您可以將該外掛包含在 vite.config.js 配置檔案中。

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3import react from '@vitejs/plugin-react';
4 
5export default defineConfig({
6 plugins: [
7 laravel(['resources/js/app.jsx']),
8 react(),
9 ],
10});

您需要確保任何包含 JSX 的檔案都具有 .jsx.tsx 副檔名,並記住按需更新您的入口點,如上文所示

您還需要在現有的 @vite 指令旁邊包含額外的 @viteReactRefresh Blade 指令。

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

@viteReactRefresh 指令必須在 @vite 指令之前呼叫。

Laravel 的 入門套件 已經包含了正確的 Laravel、React 和 Vite 配置。這些入門套件是開始使用 Laravel、React 和 Vite 最快捷的方式。

Svelte

如果您想使用 Svelte 框架構建前端,那麼您還需要安裝 @sveltejs/vite-plugin-svelte 外掛:

1npm install --save-dev @sveltejs/vite-plugin-svelte

然後,您可以將該外掛包含在 vite.config.js 配置檔案中。

1import { svelte } from '@sveltejs/vite-plugin-svelte';
2import laravel from 'laravel-vite-plugin';
3import { defineConfig } from 'vite';
4 
5export default defineConfig({
6 plugins: [
7 laravel({
8 input: ['resources/js/app.ts'],
9 ssr: 'resources/js/ssr.ts',
10 refresh: true,
11 }),
12 svelte(),
13 ],
14});

Laravel 的 入門套件 已經包含了正確的 Laravel、Svelte 和 Vite 配置。這些入門套件是開始使用 Laravel、Svelte 和 Vite 最快捷的方式。

Inertia

Laravel Vite 外掛提供了一個便捷的 resolvePageComponent 函式,以幫助您解析 Inertia 頁面元件。以下是該輔助函式在 Vue 3 中使用的示例;不過,您也可以在 React 或 Svelte 等其他框架中使用該函式:

1import { createApp, h } from 'vue';
2import { createInertiaApp } from '@inertiajs/vue3';
3import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
4 
5createInertiaApp({
6 resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
7 setup({ el, App, props, plugin }) {
8 createApp({ render: () => h(App, props) })
9 .use(plugin)
10 .mount(el)
11 },
12});

如果您在 Inertia 中使用了 Vite 的程式碼分割功能,我們建議配置 資源預取

Laravel 的 入門套件 已經包含了正確的 Laravel、Inertia 和 Vite 配置。這些入門套件是開始使用 Laravel、Inertia 和 Vite 最快捷的方式。

URL 處理

當在 HTML、CSS 或 JS 中使用 Vite 引用資源時,需要注意一些注意事項。首先,如果您使用絕對路徑引用資源,Vite 將不會把該資源包含在構建中;因此,您應該確保資源在您的公共目錄(public)中可用。使用 專門的 CSS 入口點 時,應避免使用絕對路徑,因為在開發過程中,瀏覽器會嘗試從 Vite 開發伺服器載入這些路徑,而不是從您的公共目錄載入。

引用相對資源路徑時,請記住這些路徑是相對於引用它們的檔案而言的。任何透過相對路徑引用的資源都將被 Vite 重寫、版本化和打包。

考慮以下專案結構:

1public/
2 taylor.png
3resources/
4 js/
5 Pages/
6 Welcome.vue
7 images/
8 abigail.png

以下示例演示了 Vite 如何處理相對和絕對 URL:

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

使用樣式表

Laravel 的 入門套件 已經包含了正確的 Tailwind 和 Vite 配置。或者,如果您想在不使用入門套件的情況下將 Tailwind 與 Laravel 一起使用,請檢視 Tailwind 的 Laravel 安裝指南

所有 Laravel 應用程式都已經包含了 Tailwind 和配置正確的 vite.config.js 檔案。因此,您只需要啟動 Vite 開發伺服器或執行 dev Composer 命令,它將同時啟動 Laravel 和 Vite 開發伺服器:

1composer run dev

應用程式的 CSS 可以放在 resources/css/app.css 檔案中。

使用 Blade 和路由

使用 Vite 處理靜態資源

在 JavaScript 或 CSS 中引用資源時,Vite 會自動處理並對其進行版本控制。此外,在構建基於 Blade 的應用程式時,Vite 還可以處理並版本化您僅在 Blade 模板中引用的靜態資源。

然而,為了實現這一點,您需要在外掛的 assets 選項中指定資源,從而讓 Vite 知曉它們。例如,如果您想處理並版本化儲存在 resources/images 中的所有圖片以及 resources/fonts 中的所有字型,您應該將以下內容新增到您的 Vite 配置中:

1laravel({
2 input: 'resources/js/app.js',
3 assets: ['resources/images/**', 'resources/fonts/**'],
4})

執行 npm run build 時,這些資源將由 Vite 處理。然後,您可以在 Blade 模板中使用 Vite::asset 方法引用這些資源,它將返回給定資源的版本化 URL:

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

在 Laravel Vite 外掛 3.0 版本之前,必須使用 import.meta.glob 在應用程式的入口點匯入靜態資源。assets 選項是由於 Vite 8 的變更而引入的。

儲存時自動重新整理

當您的應用程式使用傳統的 Blade 伺服器端渲染構建時,Vite 可以透過在您更改應用程式中的檢視檔案時自動重新整理瀏覽器,從而改進您的開發工作流程。要開始使用,您只需將 refresh 選項設定為 true 即可。

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel({
7 // ...
8 refresh: true,
9 }),
10 ],
11});

refresh 選項為 true 時,儲存以下目錄中的檔案將在您執行 npm run dev 時觸發瀏覽器執行全頁面重新整理:

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

如果您正在利用 Ziggy 在應用程式前端生成路由連結,監控 routes/** 目錄非常有用。

如果這些預設路徑不符合您的需求,您可以指定自己的監控路徑列表:

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel({
7 // ...
8 refresh: ['resources/views/**'],
9 }),
10 ],
11});

在底層,Laravel Vite 外掛使用了 vite-plugin-full-reload 包,它提供了一些高階配置選項來微調此功能的行為。如果您需要這種級別的自定義,可以提供 config 定義:

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel({
7 // ...
8 refresh: [{
9 paths: ['path/to/watch/**'],
10 config: { delay: 300 }
11 }],
12 }),
13 ],
14});

別名 (Aliases)

在 JavaScript 應用程式中,建立別名以指向經常引用的目錄是很常見的。但是,您也可以使用 Illuminate\Support\Facades\Vite 類上的 macro 方法建立在 Blade 中使用的別名。通常,“宏”應該在服務提供者boot 方法中定義:

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

一旦定義了宏,就可以在模板中呼叫它。例如,我們可以使用上面定義的 image 宏來引用位於 resources/images/logo.png 的資源:

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

資源預取

在使用 Vite 的程式碼分割功能構建 SPA 時,所需的資源會在每次頁面導航時獲取。這種行為可能導致 UI 渲染延遲。如果這對您選擇的前端框架是個問題,Laravel 提供了在初始頁面載入時主動預取應用程式 JavaScript 和 CSS 資源的功能。

您可以透過在服務提供者boot 方法中呼叫 Vite::prefetch 方法,來指示 Laravel 主動預取您的資源:

1<?php
2 
3namespace App\Providers;
4 
5use Illuminate\Support\Facades\Vite;
6use Illuminate\Support\ServiceProvider;
7 
8class AppServiceProvider extends ServiceProvider
9{
10 /**
11 * Register any application services.
12 */
13 public function register(): void
14 {
15 // ...
16 }
17 
18 /**
19 * Bootstrap any application services.
20 */
21 public function boot(): void
22 {
23 Vite::prefetch(concurrency: 3);
24 }
25}

在上面的示例中,資源將在每次頁面載入時以最多 3 個併發下載的速度進行預取。您可以根據應用程式的需求修改併發數,或者如果應用程式應該一次性下載所有資源,則不指定併發限制:

1/**
2 * Bootstrap any application services.
3 */
4public function boot(): void
5{
6 Vite::prefetch();
7}

預設情況下,預取將在頁面 load 事件觸發時開始。如果您想自定義預取開始的時間,可以指定一個 Vite 將要監聽的事件:

1/**
2 * Bootstrap any application services.
3 */
4public function boot(): void
5{
6 Vite::prefetch(event: 'vite:prefetch');
7}

使用上面的程式碼,當您手動在 window 物件上分派 vite:prefetch 事件時,預取就會開始。例如,您可以讓預取在頁面載入三秒後開始:

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

自定義基礎 URL

如果您的 Vite 編譯資源部署到與應用程式不同的域(例如透過 CDN),則必須在應用程式的 .env 檔案中指定 ASSET_URL 環境變數:

1ASSET_URL=https://cdn.example.com

配置資源 URL 後,所有指向您資源的重寫 URL 都將以配置的值作為字首:

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

請記住,絕對 URL 不會被 Vite 重寫,因此它們不會被新增字首。

環境變數

您可以透過在應用程式的 .env 檔案中為環境變數新增 VITE_ 字首,將它們注入到 JavaScript 中:

1VITE_SENTRY_DSN_PUBLIC=http://example.com

您可以透過 import.meta.env 物件訪問注入的環境變數:

1import.meta.env.VITE_SENTRY_DSN_PUBLIC

在測試中停用 Vite

Laravel 的 Vite 整合會嘗試在執行測試時解析您的資源,這要求您要麼執行 Vite 開發伺服器,要麼構建您的資源。

如果您希望在測試期間模擬 Vite,可以呼叫 withoutVite 方法,該方法適用於任何擴充套件了 Laravel TestCase 類的測試:

1test('without vite example', function () {
2 $this->withoutVite();
3 
4 // ...
5});
1use Tests\TestCase;
2 
3class ExampleTest extends TestCase
4{
5 public function test_without_vite_example(): void
6 {
7 $this->withoutVite();
8 
9 // ...
10 }
11}

如果您想對所有測試停用 Vite,可以從基礎 TestCase 類的 setUp 方法中呼叫 withoutVite 方法:

1<?php
2 
3namespace Tests;
4 
5use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
6 
7abstract class TestCase extends BaseTestCase
8{
9 protected function setUp(): void
10 {
11 parent::setUp();
12 
13 $this->withoutVite();
14 }
15}

伺服器端渲染 (SSR)

Laravel Vite 外掛使得使用 Vite 設定伺服器端渲染變得輕而易舉。要開始使用,請在 resources/js/ssr.js 建立一個 SSR 入口點,並透過將配置選項傳遞給 Laravel 外掛來指定該入口點:

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel({
7 input: 'resources/js/app.js',
8 ssr: 'resources/js/ssr.js',
9 }),
10 ],
11});

為確保您不會忘記重建 SSR 入口點,我們建議增強應用程式 package.json 中的“build”指令碼以建立您的 SSR 構建:

1"scripts": {
2 "dev": "vite",
3 "build": "vite build"
4 "build": "vite build && vite build --ssr"
5}

然後,要構建並啟動 SSR 伺服器,您可以執行以下命令:

1npm run build
2node bootstrap/ssr/ssr.js

如果您正在使用 Inertia 的 SSR,則可以使用 inertia:start-ssr Artisan 命令來啟動 SSR 伺服器:

1php artisan inertia:start-ssr

Laravel 的 入門套件 已經包含了正確的 Laravel、Inertia SSR 和 Vite 配置。這些入門套件是開始使用 Laravel、Inertia SSR 和 Vite 最快捷的方式。

指令碼和樣式標籤屬性

內容安全策略 (CSP) Nonce

如果您希望在指令碼和樣式標籤上包含 nonce 屬性,作為內容安全策略的一部分,您可以在自定義中介軟體中使用 useCspNonce 方法生成或指定一個 nonce:

1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Illuminate\Support\Facades\Vite;
8use Symfony\Component\HttpFoundation\Response;
9 
10class AddContentSecurityPolicyHeaders
11{
12 /**
13 * Handle an incoming request.
14 *
15 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
16 */
17 public function handle(Request $request, Closure $next): Response
18 {
19 Vite::useCspNonce();
20 
21 return $next($request)->withHeaders([
22 'Content-Security-Policy' => "script-src 'nonce-".Vite::cspNonce()."'",
23 ]);
24 }
25}

呼叫 useCspNonce 方法後,Laravel 將自動在所有生成的指令碼和樣式標籤上包含 nonce 屬性。

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

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

如果您已經有一個想要指示 Laravel 使用的 nonce,則可以將該 nonce 傳遞給 useCspNonce 方法:

1Vite::useCspNonce($nonce);

子資源完整性 (SRI)

如果您的 Vite 清單包含資源的 integrity 雜湊值,Laravel 將自動在它生成的任何指令碼和樣式標籤上新增 integrity 屬性,以強制執行子資源完整性。預設情況下,Vite 不會在其清單中包含 integrity 雜湊值,但您可以透過安裝 vite-plugin-manifest-sri NPM 外掛來啟用它。

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

然後,您可以在 vite.config.js 檔案中啟用此外掛:

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3import manifestSRI from 'vite-plugin-manifest-sri';
4 
5export default defineConfig({
6 plugins: [
7 laravel({
8 // ...
9 }),
10 manifestSRI(),
11 ],
12});

如果需要,您還可以自定義可以找到完整性雜湊的清單鍵 (manifest key):

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

如果您想完全停用此自動檢測,可以將 false 傳遞給 useIntegrityKey 方法:

1Vite::useIntegrityKey(false);

任意屬性

如果您需要在指令碼和樣式標籤上包含額外的屬性,例如 data-turbo-track 屬性,可以透過 useScriptTagAttributesuseStyleTagAttributes 方法指定它們。通常,這些方法應該從服務提供者中呼叫:

1use Illuminate\Support\Facades\Vite;
2 
3Vite::useScriptTagAttributes([
4 'data-turbo-track' => 'reload', // Specify a value for the attribute...
5 'async' => true, // Specify an attribute without a value...
6 'integrity' => false, // Exclude an attribute that would otherwise be included...
7]);
8 
9Vite::useStyleTagAttributes([
10 'data-turbo-track' => 'reload',
11]);

如果您需要有條件地新增屬性,可以傳遞一個回撥函式,該回調函式將接收資源源路徑、其 URL、其清單塊 (manifest chunk) 和整個清單:

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

當 Vite 開發伺服器執行時,$chunk$manifest 引數將為 null

高階自定義

開箱即用,Laravel 的 Vite 外掛使用了合理的約定,應該適用於大多數應用程式;然而,有時您可能需要自定義 Vite 的行為。為了啟用額外的自定義選項,我們提供了以下方法和選項,它們可以替代 @vite Blade 指令使用:

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

vite.config.js 檔案中,您應該指定相同的配置:

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel({
7 hotFile: 'storage/vite.hot', // Customize the "hot" file...
8 buildDirectory: 'bundle', // Customize the build directory...
9 input: ['resources/js/app.js'], // Specify the entry points...
10 }),
11 ],
12 build: {
13 manifest: 'assets.json', // Customize the manifest filename...
14 },
15});

開發伺服器跨域資源共享 (CORS)

如果您在瀏覽器中從 Vite 開發伺服器獲取資源時遇到跨域資源共享 (CORS) 問題,則可能需要授予您的自定義源訪問開發伺服器的許可權。Vite 結合 Laravel 外掛無需額外配置即可允許以下源:

  • ::1
  • 127.0.0.1
  • localhost
  • *.test
  • *.localhost
  • 專案 .env 中的 APP_URL

為專案允許自定義源的最簡單方法是確保應用程式的 APP_URL 環境變數與您在瀏覽器中訪問的源匹配。例如,如果您訪問 https://my-app.laravel,則應更新您的 .env 以匹配:

1APP_URL=https://my-app.laravel

如果您需要對源進行更細粒度的控制(例如支援多個源),則應利用 Vite 全面且靈活的內建 CORS 伺服器配置。例如,您可以在專案的 vite.config.js 檔案中的 server.cors.origin 配置選項中指定多個源:

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel({
7 input: 'resources/js/app.js',
8 refresh: true,
9 }),
10 ],
11 server: {
12 cors: {
13 origin: [
14 'https://backend.laravel',
15 'http://admin.laravel:8566',
16 ],
17 },
18 },
19});

您還可以包含正則表示式模式,如果您想允許給定頂級域(如 *.laravel)的所有源,這將很有幫助:

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3 
4export default defineConfig({
5 plugins: [
6 laravel({
7 input: 'resources/js/app.js',
8 refresh: true,
9 }),
10 ],
11 server: {
12 cors: {
13 origin: [
14 // Supports: SCHEME://DOMAIN.laravel[:PORT]
15 /^https?:\/\/.*\.laravel(:\d+)?$/,
16 ],
17 },
18 },
19});

修正開發伺服器 URL

Vite 生態系統中的某些外掛假定以正斜槓開頭的 URL 將始終指向 Vite 開發伺服器。然而,由於 Laravel 整合的性質,情況並非如此。

例如,當 Vite 正在為您提供資源時,vite-imagetools 外掛會輸出如下 URL:

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

vite-imagetools 外掛期望輸出的 URL 將被 Vite 攔截,然後該外掛可以處理所有以 /@imagetools 開頭的 URL。如果您使用的外掛預料到這種行為,則需要手動修正 URL。您可以透過在 vite.config.js 檔案中使用 transformOnServe 選項來完成此操作。

在這個特定示例中,我們將開發伺服器 URL 新增到生成程式碼中所有 /@imagetools 出現的位置之前:

1import { defineConfig } from 'vite';
2import laravel from 'laravel-vite-plugin';
3import { imagetools } from 'vite-imagetools';
4 
5export default defineConfig({
6 plugins: [
7 laravel({
8 // ...
9 transformOnServe: (code, devServerUrl) => code.replaceAll('/@imagetools', devServerUrl+'/@imagetools'),
10 }),
11 imagetools(),
12 ],
13});

現在,當 Vite 提供資源時,它將輸出指向 Vite 開發伺服器的 URL:

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