翻译进度
18
分块数量
1
参与人数

资源打包

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


资源打包

简介

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

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

安装与配置

[!注意]
以下文档介绍了如何手动安装和配置 Laravel Vite 插件。不过,Laravel 的 入门套件 已经包含了所有这些基础配置内容,是开始使用 Laravel 和 Vite 的最快方式。

无与伦比 翻译于 9小时前

安装 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-react@sveltejs/vite-plugin-svelte@vitejs/plugin-vue

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',
        ]),
    ],
});
无与伦比 翻译于 9小时前

如果你正在构建一个 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 并且已经对你的应用程序运行了安全命令,那么 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]
});
无与伦比 翻译于 8小时前

If you are unable to generate a trusted certificate for your system, you may install and configure the @vitejs/plugin-basic-ssl plugin. When using untrusted certificates, you will need to accept the certificate warning for Vite's development server in your browser by following the "Local" link in your console when running the npm run dev command.

Running the Development Server in Sail on WSL2

When running the Vite development server within Laravel Sail on Windows Subsystem for Linux 2 (WSL2), you should add the following configuration to your vite.config.js file to ensure the browser can communicate with the development server:

// ...

export default defineConfig({
    // ...
    server: { // [tl! add:start]
        hmr: {
            host: 'localhost',
        },
    }, // [tl! add:end]
});

If your file changes are not being reflected in the browser while the development server is running, you may also need to configure Vite's server.watch.usePolling option.

Loading Your Scripts and Styles

With your Vite entry points configured, you may now reference them in a @vite() Blade directive that you add to the <head> of your application's root template:

<!DOCTYPE html>
<head>
    {{-- ... --}}

    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

If you're importing your CSS via JavaScript, you only need to include the JavaScript entry point:

<!DOCTYPE html>
<head>
    {{-- ... --}}

    @vite('resources/js/app.js')
</head>

The @vite directive will automatically detect the Vite development server and inject the Vite client to enable Hot Module Replacement. In build mode, the directive will load your compiled and versioned assets, including any imported CSS.

If needed, you may also specify the build path of your compiled assets when invoking the @vite directive:

<!doctype html>
<head>
    {{-- Given build path is relative to public path. --}}

    @vite('resources/js/app.js', 'vendor/courier/build')
</head>

Inline Assets

Sometimes it may be necessary to include the raw content of assets rather than linking to the versioned URL of the asset. For example, you may need to include asset content directly into your page when passing HTML content to a PDF generator. You may output the content of Vite assets using the content method provided by the Vite facade:

@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>

Running Vite

There are two ways you can run Vite. You may run the development server via the dev command, which is useful while developing locally. The development server will automatically detect changes to your files and instantly reflect them in any open browser windows.

Or, running the build command will version and bundle your application's assets and get them ready for you to deploy to production:

# Run the Vite development server...
npm run dev

# Build and version the assets for production...
npm run build

If you are running the development server in Sail on WSL2, you may need some additional configuration options.

Working With JavaScript

Aliases

By default, The Laravel plugin provides a common alias to help you hit the ground running and conveniently import your application's assets:

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

You may overwrite the '@' alias by adding your own to the vite.config.js configuration file:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

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

Vue

If you would like to build your frontend using the Vue framework, then you will also need to install the @vitejs/plugin-vue plugin:

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

You may then include the plugin in your vite.config.js configuration file. There are a few additional options you will need when using the Vue plugin with 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's starter kits already include the proper Laravel, Vue, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Vue, and Vite.

React

If you would like to build your frontend using the React framework, then you will also need to install the @vitejs/plugin-react plugin:

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

You may then include the plugin in your vite.config.js configuration file:

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

You will need to ensure that any files containing JSX have a .jsx or .tsx extension, remembering to update your entry point, if required, as shown above.

You will also need to include the additional @viteReactRefresh Blade directive alongside your existing @vite directive.

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

The @viteReactRefresh directive must be called before the @vite directive.

[!NOTE]
Laravel's starter kits already include the proper Laravel, React, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, React, and Vite.

Svelte

If you would like to build your frontend using the Svelte framework, then you will also need to install the @sveltejs/vite-plugin-svelte plugin:

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

You may then include the plugin in your vite.config.js configuration file.

import { svelte } from '@sveltejs/vite-plugin-svelte';
import laravel from 'laravel-vite-plugin';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    laravel({
      input: ['resources/js/app.ts'],
      ssr: 'resources/js/ssr.ts',
      refresh: true,
    }),
    svelte(),
  ],
});

[!NOTE]
Laravel's starter kits already include the proper Laravel, Svelte, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Svelte, and Vite.

Inertia

The Laravel Vite plugin provides a convenient resolvePageComponent function to help you resolve your Inertia page components. Below is an example of the helper in use with Vue 3; however, you may also utilize the function in other frameworks such as React or Svelte:

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

If you are using Vite's code splitting feature with Inertia, we recommend configuring asset prefetching.

[!NOTE]
Laravel's starter kits already include the proper Laravel, Inertia, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Inertia, and Vite.

URL Processing

When using Vite and referencing assets in your application's HTML, CSS, or JS, there are a couple of caveats to consider. First, if you reference assets with an absolute path, Vite will not include the asset in the build; therefore, you should ensure that the asset is available in your public directory. You should avoid using absolute paths when using a dedicated CSS entrypoint because, during development, browsers will try to load these paths from the Vite development server, where the CSS is hosted, rather than from your public directory.

When referencing relative asset paths, you should remember that the paths are relative to the file where they are referenced. Any assets referenced via a relative path will be re-written, versioned, and bundled by Vite.

Consider the following project structure:

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

The following example demonstrates how Vite will treat relative and absolute URLs:

<!-- 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">

Working With Stylesheets

[!NOTE]
Laravel's starter kits already include the proper Tailwind and Vite configuration. Or, if you would like to use Tailwind and Laravel without using one of our starter kits, check out Tailwind's installation guide for Laravel.

All Laravel applications already include Tailwind and a properly configured vite.config.js file. So, you only need to start the Vite development server or run the dev Composer command, which will start both the Laravel and Vite development servers:

composer run dev

Your application's CSS may be placed within the resources/css/app.css file.

Working With Blade and Routes

Processing Static Assets With Vite

When referencing assets in your JavaScript or CSS, Vite automatically processes and versions them. In addition, when building Blade based applications, Vite can also process and version static assets that you reference solely in Blade templates.

However, in order to accomplish this, you need to make Vite aware of your assets by specifying them in the plugin's assets option. For example, if you want to process and version all images stored in resources/images and all fonts stored in resources/fonts, you should add the following to your Vite configuration:

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

These assets will now be processed by Vite when running npm run build. You can then reference these assets in Blade templates using the Vite::asset method, which will return the versioned URL for a given asset:

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

[!NOTE]
Prior to version 3 of the Laravel Vite plugin, static assets had to be imported in your application's entry point using import.meta.glob. The assets option was introduced due to changes in Vite 8.

Refreshing on Save

When your application is built using traditional server-side rendering with Blade, Vite can improve your development workflow by automatically refreshing the browser when you make changes to view files in your application. To get started, you can simply specify the refresh option as true.

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            // ...
            refresh: true,
        }),
    ],
});

When the refresh option is true, saving files in the following directories will trigger the browser to perform a full page refresh while you are running npm run dev:

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

Watching the routes/** directory is useful if you are utilizing Ziggy to generate route links within your application's frontend.

If these default paths do not suit your needs, you can specify your own list of paths to watch:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

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

Under the hood, the Laravel Vite plugin uses the vite-plugin-full-reload package, which offers some advanced configuration options to fine-tune this feature's behavior. If you need this level of customization, you may provide a config definition:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

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

Aliases

It is common in JavaScript applications to create aliases to regularly referenced directories. But, you may also create aliases to use in Blade by using the macro method on the Illuminate\Support\Facades\Vite class. Typically, "macros" should be defined within the boot method of a service provider:

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

Once a macro has been defined, it can be invoked within your templates. For example, we can use the image macro defined above to reference an asset located at resources/images/logo.png:

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

Asset Prefetching

When building an SPA using Vite's code splitting feature, required assets are fetched on each page navigation. This behavior can lead to delayed UI rendering. If this is a problem for your frontend framework of choice, Laravel offers the ability to eagerly prefetch your application's JavaScript and CSS assets on initial page load.

You can instruct Laravel to eagerly prefetch your assets by invoking the Vite::prefetch method in the boot method of a service provider:

<?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);
    }
}

In the example above, assets will be prefetched with a maximum of 3 concurrent downloads on each page load. You can modify the concurrency to suit your application's needs or specify no concurrency limit if the application should download all assets at once:

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

By default, prefetching will begin when the page load event fires. If you would like to customize when prefetching begins, you may specify an event that Vite will listen for:

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

Given the code above, prefetching will now begin when you manually dispatch the vite:prefetch event on the window object. For example, you could have prefetching begin three seconds after the page loads:

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

Custom Base URLs

If your Vite compiled assets are deployed to a domain separate from your application, such as via a CDN, you must specify the ASSET_URL environment variable within your application's .env file:

ASSET_URL=https://cdn.example.com

After configuring the asset URL, all re-written URLs to your assets will be prefixed with the configured value:

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

Remember that absolute URLs are not re-written by Vite, so they will not be prefixed.

Environment Variables

You may inject environment variables into your JavaScript by prefixing them with VITE_ in your application's .env file:

VITE_SENTRY_DSN_PUBLIC=http://example.com

You may access injected environment variables via the import.meta.env object:

import.meta.env.VITE_SENTRY_DSN_PUBLIC

Disabling Vite in Tests

Laravel's Vite integration will attempt to resolve your assets while running your tests, which requires you to either run the Vite development server or build your assets.

If you would prefer to mock Vite during testing, you may call the withoutVite method, which is available for any tests that extend Laravel's TestCase class:

test('without vite example', function () {
    $this->withoutVite();

    // ...
});
use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_without_vite_example(): void
    {
        $this->withoutVite();

        // ...
    }
}

If you would like to disable Vite for all tests, you may call the withoutVite method from the setUp method on your base TestCase class:

<?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]
}

Server-Side Rendering (SSR)

The Laravel Vite plugin makes it painless to set up server-side rendering with Vite. To get started, create an SSR entry point at resources/js/ssr.js and specify the entry point by passing a configuration option to the Laravel plugin:

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

To ensure you don't forget to rebuild the SSR entry point, we recommend augmenting the "build" script in your application's package.json to create your SSR build:

"scripts": {
     "dev": "vite",
     "build": "vite build" // [tl! remove]
     "build": "vite build && vite build --ssr" // [tl! add]
}

Then, to build and start the SSR server, you may run the following commands:

npm run build
node bootstrap/ssr/ssr.js

If you are using SSR with Inertia, you may instead use the inertia:start-ssr Artisan command to start the SSR server:

php artisan inertia:start-ssr

[!NOTE]
Laravel's starter kits already include the proper Laravel, Inertia SSR, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Inertia SSR, and Vite.

Script and Style Tag Attributes

Content Security Policy (CSP) Nonce

If you wish to include a nonce attribute on your script and style tags as part of your Content Security Policy, you may generate or specify a nonce using the useCspNonce method within a custom middleware:

<?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()."'",
        ]);
    }
}

After invoking the useCspNonce method, Laravel will automatically include the nonce attributes on all generated script and style tags.

If you need to specify the nonce elsewhere, including the Ziggy @route directive included with Laravel's starter kits, you may retrieve it using the cspNonce method:

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

If you already have a nonce that you would like to instruct Laravel to use, you may pass the nonce to the useCspNonce method:

Vite::useCspNonce($nonce);

Subresource Integrity (SRI)

If your Vite manifest includes integrity hashes for your assets, Laravel will automatically add the integrity attribute on any script and style tags it generates in order to enforce Subresource Integrity. By default, Vite does not include the integrity hash in its manifest, but you may enable it by installing the vite-plugin-manifest-sri NPM plugin:

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

You may then enable this plugin in your vite.config.js file:

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

If required, you may also customize the manifest key where the integrity hash can be found:

use Illuminate\Support\Facades\Vite;

Vite::useIntegrityKey('custom-integrity-key');

If you would like to disable this auto-detection completely, you may pass false to the useIntegrityKey method:

Vite::useIntegrityKey(false);

Arbitrary Attributes

If you need to include additional attributes on your script and style tags, such as the data-turbo-track attribute, you may specify them via the useScriptTagAttributes and useStyleTagAttributes methods. Typically, this methods should be invoked from a service provider:

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

If you need to conditionally add attributes, you may pass a callback that will receive the asset source path, its URL, its manifest chunk, and the entire manifest:

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

[!WARNING]
The $chunk and $manifest arguments will be null while the Vite development server is running.

Advanced Customization

Out of the box, Laravel's Vite plugin uses sensible conventions that should work for the majority of applications; however, sometimes you may need to customize Vite's behavior. To enable additional customization options, we offer the following methods and options which can be used in place of the @vite Blade directive:

<!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>

Within the vite.config.js file, you should then specify the same configuration:

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

Dev Server Cross-Origin Resource Sharing (CORS)

If you are experiencing Cross-Origin Resource Sharing (CORS) issues in the browser while fetching assets from the Vite dev server, you may need to grant your custom origin access to the dev server. Vite combined with the Laravel plugin allows the following origins without any additional configuration:

  • ::1
  • 127.0.0.1
  • localhost
  • *.test
  • *.localhost
  • APP_URL in the project's .env

The easiest way to allow a custom origin for your project is to ensure that your application's APP_URL environment variable matches the origin you are visiting in your browser. For example, if you visiting https://my-app.laravel, you should update your .env to match:

APP_URL=https://my-app.laravel

If you need more fine-grained control over the origins, such as supporting multiple origins, you should utilize Vite's comprehensive and flexible built-in CORS server configuration. For example, you may specify multiple origins in the server.cors.origin configuration option in the project's vite.config.js file:

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

You may also include regex patterns, which can be helpful if you would like to allow all origins for a given top-level domain, such as *.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]
});

Correcting Dev Server URLs

Some plugins within the Vite ecosystem assume that URLs which begin with a forward-slash will always point to the Vite dev server. However, due to the nature of the Laravel integration, this is not the case.

For example, the vite-imagetools plugin outputs URLs like the following while Vite is serving your assets:

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

The vite-imagetools plugin is expecting that the output URL will be intercepted by Vite and the plugin may then handle all URLs that start with /@imagetools. If you are using plugins that are expecting this behavior, you will need to manually correct the URLs. You can do this in your vite.config.js file by using the transformOnServe option.

In this particular example, we will prepend the dev server URL to all occurrences of /@imagetools within the generated code:

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

Now, while Vite is serving Assets, it will output URLs that point to the Vite dev server:

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

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~