Readouble

Laravel 10.x アセットの構築(Vite)

イントロダクションIntroduction

Viteは、非常に高速な開発環境を提供してくれる、コードを本番用に構築する最新のフロントエンド・ビルド・ツールです。Laravelでアプリケーションを構築する場合、通常、Viteを使用してアプリケーションのCSSとJavaScriptファイルを本番環境用のアセットへ構築することになります。Vite[https://vitejs.dev] is a modern frontend build tool that provides an extremely fast development environment and bundles your code for production. When building applications with Laravel, you will typically use Vite to bundle your application's CSS and JavaScript files into production ready assets.

Laravelは、開発および実働用アセットをロードするため、公式プラグインとBladeディレクティブを提供し、Viteをシームレスに統合しています。Laravel integrates seamlessly with Vite by providing an official plugin and Blade directive to load your assets for development and production.

lightbulb Note: Laravel Mixを実行していますか?新しいLaravelのインストールでは、Laravel MixをViteへ置き換えました。Mixのドキュメントは、Laravel Mixのウェブサイトをご覧ください。Viteに切り替えたい場合は、移行ガイドを参照してください。[!NOTE]
Are you running Laravel Mix? Vite has replaced Laravel Mix in new Laravel installations. For Mix documentation, please visit the Laravel Mix[https://laravel-mix.com/] website. If you would like to switch to Vite, please see our migration guide[https://github.com/laravel/vite-plugin/blob/main/UPGRADE.md#migrating-from-laravel-mix-to-vite].

ViteとLaravel Mixの選択Choosing Between Vite and Laravel Mix

Viteへ移行する前、新しいLaravelアプリケーションは、アセットをバンドルする際にwebpackで動作するMixを使用していました。Viteは、リッチなJavaScriptアプリケーションを構築する際に、より速く、より生産的な体験を提供することに重点を置いています。Inertia のようなツールで開発したものを含め、シングルページアプリケーション(SPA)を開発している場合、Viteは完璧にフィットするでしょう。Before transitioning to Vite, new Laravel applications utilized Mix[https://laravel-mix.com/], which is powered by webpack[https://webpack.js.org/], when bundling assets. Vite focuses on providing a faster and more productive experience when building rich JavaScript applications. If you are developing a Single Page Application (SPA), including those developed with tools like Inertia[https://inertiajs.com], Vite will be the perfect fit.

Viteは、Livewire和訳)を使用したものを含む、JavaScriptを「ふりかけ」程度に使った従来のサーバサイドレンダリングアプリケーションでもうまく機能します。しかし、Laravel Mixがサポートしている、JavaScriptアプリケーションで直接参照されていない任意のアセットをビルドにコピーする機能など、いくつかの機能が欠落しています。Vite also works well with traditional server-side rendered applications with JavaScript "sprinkles", including those using Livewire[https://livewire.laravel.com]. However, it lacks some features that Laravel Mix supports, such as the ability to copy arbitrary assets into the build that are not referenced directly in your JavaScript application.

Mixへ戻すMigrating Back to Mix

Vite scaffoldingを使用して新しいLaravelアプリケーションを開始したが、Laravel Mixとwebpackへ戻る必要があるのですか?大丈夫です。ViteからMixへの移行に関する公式ガイドを参照してください。Have you started a new Laravel application using our Vite scaffolding but need to move back to Laravel Mix and webpack? No problem. Please consult our official guide on migrating from Vite to Mix[https://github.com/laravel/vite-plugin/blob/main/UPGRADE.md#migrating-from-vite-to-laravel-mix].

インストールと準備Installation & Setup

lightbulb Note: 以下のドキュメントでは、Laravel Viteプラグインを手作業でインストールし、設定する方法について説明しています。しかし、Laravelのスターターキットには、すでにこのスカフォールドがすべて含まれており、LaravelとViteを始める最速の方法を用意しています。[!NOTE]
The following documentation discusses how to manually install and configure the Laravel Vite plugin. However, Laravel's starter kits[/docs/{{version}}/starter-kits] already include all of this scaffolding and are the fastest way to get started with Laravel and Vite.

NodeのインストールInstalling Node

ViteとLaravelプラグインを実行する前に、Node.js(16以降)とNPMを確実にインストールしてください。You must ensure that Node.js (16 ) and NPM are installed before running Vite and the Laravel plugin:

node -v
npm -v

NodeとNPMの最新版は、Node公式サイトからグラフィカルインストーラを使って簡単にインストールできます。また、Laravel Sailを使用している場合は、SailからNodeとNPMを呼び出せます。You can easily install the latest version of Node and NPM using simple graphical installers from the official Node website[https://nodejs.org/en/download/]. Or, if you are using Laravel Sail[https://laravel.com/docs/{{version}}/sail], you may invoke Node and NPM through Sail:

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

ViteとLaravelプラグインのインストールInstalling Vite and the Laravel Plugin

Laravelを新規にインストールすると、アプリケーションのディレクトリ構造のルートにpackage.jsonファイルができます。デフォルトのpackage.jsonファイルは、ViteとLaravelプラグインを使い始めるために必要なものを既に含んでいます。アプリケーションのフロントエンドの依存関係は、NPM経由でインストールできます。Within a fresh installation of Laravel, you will find a package.json file in the root of your application's directory structure. The default package.json file already includes everything you need to get started using Vite and the Laravel plugin. You may install your application's frontend dependencies via NPM:

npm install

Viteの設定Configuring Vite

Viteは、プロジェクトルートのvite.config.jsファイルで設定します。また、アプリケーションが必要とする他のプラグイン、例えば、@vitejs/plugin-vue@vitejs/plugin-reactをインストールすることもできます。Vite is configured via a vite.config.js file in the root of your project. You are free to customize this file based on your needs, and you may also install any other plugins your application requires, such as @vitejs/plugin-vue or @vitejs/plugin-react.

Laravel Viteプラグインでは、アプリケーションのエントリーポイントを指定する必要があります。これらは、JavaScriptまたはCSSファイルであり、TypeScript、JSX、TSX、Sassなどのプリプロセス言語が含まれます。The Laravel Vite plugin requires you to specify the entry points for your application. These may be JavaScript or CSS files, and include preprocessed languages such as TypeScript, JSX, TSX, and Sass.

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

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

Inertiaを使用したアプリケーションを含むSPAを構築する場合、ViteはCSSエントリポイントなしで最適に動作します。If you are building an SPA, including applications built using Inertia, Vite works best without CSS entry points:

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 ファイルで行います。Instead, you should import your CSS via JavaScript. Typically, this would be done in your application's resources/js/app.js file:

import './bootstrap';
import '../css/app.css'; // [tl! add]

また、Laravelプラグインは複数のエントリーポイントに対応し、SSRエントリーポイントなどの高度な設定オプションにも対応しています。The Laravel plugin also supports multiple entry points and advanced configuration options such as SSR entry points[#ssr].

セキュアな開発サーバの取り扱いWorking With a Secure Development Server

ローカル開発用Webサーバが、HTTPSでアプリケーションを提供している場合、Vite開発用サーバの接続に問題が発生することがあります。If your local development web server is serving your application via HTTPS, you may run into issues connecting to the Vite development server.

Laravel Herdを使用していて、サイトをセキュアにしている場合、またはLaravel Valetを使用していて、アプリケーションに対してsecureコマンドを実行している場合、Laravel Viteプラグインが自動的に検出し、生成したTLS証明書を使用します。If you are using Laravel Herd[https://herd.laravel.com] and have secured the site or you are using Laravel Valet[/docs/{{version}}/valet] and have run the secure command[/docs/{{version}}/valet#securing-sites] against your application, the Laravel Vite plugin will automatically detect and use the generated TLS certificate for you.

アプリケーションのディレクトリ名と一致しないホストを使用してサイトをセキュアにしている場合、アプリケーションのvite.config.jsファイルにより、ホストを手作業で指定してください。If you secured the site using a host that does not match the application's directory name, you may manually specify the host in your application's vite.config.js file:

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

export default defineConfig({
    plugins: [
        laravel({
            // ...
            detectTls: 'my-app.test', // [tl! add]
        }),
    ],
});

他のWebサーバを使用する場合は、信頼できる証明書を生成し、その生成した証明書を使用するようにViteを手作業で設定する必要があります。When using another web server, you should generate a trusted certificate and manually configure Vite to use the generated certificates:

// ...
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プラグインをインストールし、設定してください。信頼できない証明書を使用する場合は、npm run devコマンドを実行する際にコンソールの"Local"リンクをたどり、ブラウザからVite開発サーバが出す証明書の警告を受け入れる必要があります。If you are unable to generate a trusted certificate for your system, you may install and configure the @vitejs/plugin-basic-ssl plugin[https://github.com/vitejs/vite-plugin-basic-ssl]. 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.

WSL2上のSailの中で開発サーバを実行するRunning the Development Server in Sail on WSL2

Windows Subsystem for Linux 2(WSL2)上のLaravel Sail内で、Vite 開発サーバを実行する場合は、ブラウザが開発サーバと通信できるようにvite.config.jsファイルへ以下の設定を追加する必要があります。When running the Vite development server within Laravel Sail[/docs/{{version}}/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]
});

開発サーバ実行中に、ファイルの変更がブラウザへ反映されない場合は、Viteのserver.watch.usePollingオプションの設定も必要です。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[https://vitejs.dev/config/server-options.html#server-watch].

スクリプトとスタイルの読み込みLoading Your Scripts and Styles

Viteのエントリーポイントを設定したら、アプリケーションのルートテンプレートの<head>@vite() Bladeディレクティブを追加し、参照できるようになります。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>

JavaScriptでCSSをインポートする場合は、JavaScriptのエントリーポイントのみを記載するだけです。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>

@vite ディレクティブは、Vite開発サーバを自動的に検出し、Viteクライアントを注入してホットモジュール置換を有効にします。ビルドモードでは、このディレクティブはインポートしたCSSを含む、コンパイル済みのバージョン管理しているアセットを読み込みます。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.

必要であれば、@viteディレクティブを呼び出す際に、コンパイル済みアセットのビルドパスを指定することもできます。If needed, you may also specify the build path of your compiled assets when invoking the @vite directive:

<!doctype html>
<head>
    {{-- 指定するビルドパスは、publicパスからの相対パス --}}

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

インラインのアセットInline Assets

時には、アセットでバージョン管理したURLへリンクするのではなく、アセットの素のコンテンツを含める必要があるかもしれません。例えば、HTMLコンテンツをPDFジェネレータに渡すときに、アセットコンテンツを直接ページに含める必要があるかもしれません。Viteファサードが提供するcontentメソッドを使用して、Viteアセットのコンテンツを出力できます。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:

@php
use Illuminate\Support\Facades\Vite;
@endphp

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

    <style>
        {!! Vite::content('resources/css/app.css') !!}
    </style>
    <script>
        {!! Vite::content('resources/js/app.js') !!}
    </script>
</head>

Viteの実行Running Vite

Viteを起動する方法は2つあります。devコマンドで開発サーバを起動するのは、ローカルで開発する際に便利です。開発サーバは、ファイルの変更を自動的に検出し、開いているブラウザウィンドウへ即座に反映させます。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.

もしくは、buildコマンドを実行すると、アプリケーションのアセットをバージョン付けして構築し、本番環境にデプロイできる状態にします。Or, running the build command will version and bundle your application's assets and get them ready for you to deploy to production:

# Viteを開発サーバで実行する
npm run dev

# 実働用にアセットをバンドルし、バージョン付けする
npm run build

WSL2上のSailで開発サーバを動作させている場合、いくつかの追加設定オプションが必要です。If you are running the development server in Sail[/docs/{{version}}/sail] on WSL2, you may need some additional configuration[#configuring-hmr-in-sail-on-wsl2] options.

JavaScriptの操作Working With JavaScript

エイリアスAliases

デフォルトでLaravelプラグインは、アプリケーションのアセットを便利にインポートできるように、共用エイリアスを提供します。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'
}

設定ファイルvite.config.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',
        },
    },
});

VueVue

Vueフレームワークを使用してフロントエンドを構築したい場合は、@vitejs/plugin-vueプラグインもインストールする必要があります。If you would like to build your frontend using the Vue[https://vuejs.org/] framework, then you will also need to install the @vitejs/plugin-vue plugin:

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

続いて、vite.config.js設定ファイルの中で、プラグインをインクルードしてください。Laravelで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: {
                    // Vueプラグインは、Single File Componentsで
                    // 参照する場合、アセットのURLをLaravelのWebサーバを
                    // 指すように書き換えます。
                    // これを`null`に設定すると、Laravelプラグインは
                    // アセットURLをViteサーバを指すように書き換えます。
                    base: null,

                    // Vueプラグインは、絶対URLを解析し、ディスク上のファイルへの
                    // 絶対パスとして扱います。
                    // これを`false`に設定すると、絶対URLはそのままになり、
                    // 期待通りにpublicディレクトリの中で、アセットへ参照できます。
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

lightbulb Note: Laravelのスターターキットには、すでに適切なLaravel、Vue、Viteの構成が含まれています。Laravel、Vue、Viteを最速で使い始めるには、Laravel Breezeをチェックしてください。[!NOTE]
Laravel's starter kits[/docs/{{version}}/starter-kits] already include the proper Laravel, Vue, and Vite configuration. Check out Laravel Breeze[/docs/{{version}}/starter-kits#breeze-and-inertia] for the fastest way to get started with Laravel, Vue, and Vite.

ReactReact

Reactフレームワークを使用してフロントエンドを構築したい場合、@vitejs/plugin-reactプラグインもインストールする必要があります。If you would like to build your frontend using the React[https://reactjs.org/] framework, then you will also need to install the @vitejs/plugin-react plugin:

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

その後、vite.config.js設定ファイル中で、プラグインをインクルードしてください。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(),
    ],
});

JSXを含むすべてのファイルの拡張子を確実に、.jsxまたは.tsxにし、必要であれば上記のように、エントリポイントの更新を忘れないでください。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[#configuring-vite].

更に、既存の@viteディレクティブと一緒に、追加で@viteReactRefresh Bladeディレクティブをインクルードする必要があります。You will also need to include the additional @viteReactRefresh Blade directive alongside your existing @vite directive.

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

@viteReactRefreshディレクティブは、@viteディレクティブの前に呼び出す必要があります。The @viteReactRefresh directive must be called before the @vite directive.

lightbulb Note: Laravelのスターターキットには、すでに適切なLaravel、React、Viteの設定が含まれています。Laravel、React、Viteを最速で始めるには、Laravel Breeze をチェックしてください。[!NOTE]
Laravel's starter kits[/docs/{{version}}/starter-kits] already include the proper Laravel, React, and Vite configuration. Check out Laravel Breeze[/docs/{{version}}/starter-kits#breeze-and-inertia] for the fastest way to get started with Laravel, React, and Vite.

InertiaInertia

Laravel Viteプラグインは、Inertiaページコンポーネントを解決するのに便利な resolvePageComponent 関数を提供しています。以下はVue 3で使用するヘルパの例ですが、Reactなど他のフレームワークでもこの関数を利用することができます。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:

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 }) {
    return createApp({ render: () => h(App, props) })
      .use(plugin)
      .mount(el)
  },
});

lightbulb Note: Laravelのスターターキットには、すでに適切なLaravel、Inertia、Viteの構成が含まれています。Laravel、Inertia、Viteを最速で始めるには、Laravel Breeze をチェックしてください。[!NOTE]
Laravel's starter kits[/docs/{{version}}/starter-kits] already include the proper Laravel, Inertia, and Vite configuration. Check out Laravel Breeze[/docs/{{version}}/starter-kits#breeze-and-inertia] for the fastest way to get started with Laravel, Inertia, and Vite.

URL処理URL Processing

Viteを使用して、アプリケーションのHTML、CSS、JSアセットを参照する場合、いくつか考慮すべき注意点があります。まず、絶対パスでアセットを参照した場合、Viteはそのアセットをビルドに含めません。したがって、そのアセットがパブリックディレクトリで利用可能であることを確認する必要があります。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.

相対パスで参照する場合、参照するファイルからの相対パスであることを覚えておく必要があります。相対パスで参照されたアセットは、Viteによって書き直され、バージョン付けされ、バンドルされます。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

以下の例は、Viteが相対URLと絶対URLをどのように扱うかを示しています。The following example demonstrates how Vite will treat relative and absolute URLs:

<!-- このアセットをViteは扱わず、バンドルへ含まれない -->
<img src="/taylor.png">

<!-- このアセットは書き換えられ、バージョン付けし、バンドルへ含まれる -->
<img src="../../images/abigail.png">

スタイルシートの操作Working With Stylesheets

ViteのCSSサポートは、Viteドキュメント で詳しく説明されています。TailwindのようなPostCSSプラグインを使用している場合、プロジェクトのルートにpostcss.config.jsファイルを作成すると、Vite が自動的にそれを適用してくれます。You can learn more about Vite's CSS support within the Vite documentation[https://vitejs.dev/guide/features.html#css]. If you are using PostCSS plugins such as Tailwind[https://tailwindcss.com], you may create a postcss.config.js file in the root of your project and Vite will automatically apply it:

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

lightbulb Note: Laravelのスターターキットには、最初から適切なTailwind、PostCSS、Viteの構成を用意しています。また、スターターキットを使わずにTailwindとLaravelを使いたい場合は、LaravelのためのTailwindインストールガイドをチェックしてください。[!NOTE]
Laravel's starter kits[/docs/{{version}}/starter-kits] already include the proper Tailwind, PostCSS, 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[https://tailwindcss.com/docs/guides/laravel].

Bladeとルートの操作Working With Blade and Routes

Viteによる静的アセットの処理Processing Static Assets With Vite

JavaScriptやCSSのアセットを参照する場合、Viteは自動的に処理し、バージョン付けを行います。また、Bladeベースのアプリケーションを構築する場合、Bladeのテンプレート内だけで参照する静的なアセットも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.

これを実現するには、アプリケーションのエントリポイントで静的アセットをインポートすることにより、Viteにあなたの資産を認識させる必要があります。例えば、resources/imagesに格納しているすべての画像と、resources/fontsに保存しているすべてのフォントを処理してバージョン付けする場合、アプリケーションのresources/js/app.jsエントリーポイントへ以下を追加してください。However, in order to accomplish this, you need to make Vite aware of your assets by importing the static assets into the application's entry point. 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 in your application's resources/js/app.js entry point:

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

これでnpm run buildの実行時、Viteはこれらのアセットを処理するようになります。そして、BladeテンプレートではVite::assetメソッドを使用してこれらのアセットを参照でき、指定したアセットのバージョン付けを含むURLを返します。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') }}">

保存時の再描写Refreshing on Save

Bladeを用いる従来のサーバサイドレンダリングによりアプリケーションを構築している場合、アプリケーション内のビューファイルを変更したときに、自動でブラウザを再ロードすることにより、Viteは開発ワークフローを改善します。これを使用するには、refreshオプションをtrueへ指定するだけです。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,
        }),
    ],
});

refreshオプションがtrueの場合、npm run dev実行時に以下のディレクトリへファイルを保存すると、ブラウザでページがフルリフレッシュされます。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/View/Components/**app/View/Components/**
  • lang/**lang/**
  • resources/lang/**resources/lang/**
  • resources/views/**resources/views/**
  • routes/**routes/**

Ziggyを利用して、アプリケーションのフロントエンドでルートリンクを生成する場合、routes/**ディレクトリを監視すると便利です。Watching the routes/** directory is useful if you are utilizing Ziggy[https://github.com/tighten/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/**'],
        }),
    ],
});

Laravel Viteプラグインの内部では、vite-plugin-full-reloadパッケージを使用しており、この機能の動作を微調整するために高度な設定オプションを用意しています。このレベルのカスタマイズが必要な場合は、config定義を指定してください。Under the hood, the Laravel Vite plugin uses the vite-plugin-full-reload[https://github.com/ElMassimo/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

JavaScriptアプリケーションでは、定期的に参照するディレクトリにエイリアスを作成することが一般的です。しかし、Illuminate\Support\Facades\Viteクラスのmacroメソッドを使用して、Bladeで使用するエイリアスを作成することもできます。通常、「マクロ」は、サービスプロバイダbootメソッド内で定義する必要があります。It is common in JavaScript applications to create aliases[#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[/docs/{{version}}/providers]:

/**
 * 全アプリケーションサービスの初期起動処理
 */
public function boot(): void
{
    Vite::macro('image', fn (string $asset) => $this->asset("resources/images/{$asset}"));
}

一度マクロを定義したら、テンプレート内で呼び出せます。例えば、上で定義したimageマクロを使用して、resources/images/logo.pngにあるアセットを参照してみましょう。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">

ベースURLのカスタマイズCustom Base URLs

ViteでコンパイルしたアセットをCDN経由など、アプリケーションとは別のドメインにデプロイする場合は、アプリケーションの.envファイル内にASSET_URL環境変数を指定する必要があります。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

アセットURLを設定すると、アセットを指す全ての書き換えられるURLの先頭に、設定した値が付きます。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

絶対URLはViteで書き直されないため、プリフィックスが付かないことを覚えておいてください。Remember that absolute URLs are not re-written by Vite[#url-processing], so they will not be prefixed.

環境変数Environment Variables

アプリケーションの.envファイルに、VITE_ というプレフィックスを付ける環境変数を設置することで、それらの環境変数をJavaScriptへ注入できます。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

注入された環境変数は、import.meta.envオブジェクトを介してアクセスできます。You may access injected environment variables via the import.meta.env object:

import.meta.env.VITE_SENTRY_DSN_PUBLIC

テスト時のVite無効Disabling Vite in Tests

LaravelのVite統合は、テストの実行中にアセットを解決しようとするので、Vite開発サーバを実行するか、アセットをビルドする必要があります。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.

テスト中にViteをモックしたい場合は、LaravelのTestCaseクラスを拡張するすべてのテストで利用できる、withoutViteメソッドを呼び出してください。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:

use Tests\TestCase;

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

        // ...
    }
}

すべてのテストで Vite を無効にしたい場合は、ベースとなるTestCaseクラスのsetUpメソッドから、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
{
    use CreatesApplication;

    protected function setUp(): void// [tl! add:start]
    {
        parent::setUp();

        $this->withoutVite();
    }// [tl! add:end]
}

サーバサイドレンダリング(SSR)Server-Side Rendering (SSR)

Laravel Viteプラグインを使用すると、Viteでサーバサイドレンダリングを簡単に設定できます。まず、SSRエントリーポイントをresources/js/ssr.jsに作成し、Laravelプラグインに設定オプションを渡して、エントリーポイントを指定します。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',
        }),
    ],
});

SSRエントリポイントの再構築を忘れないようにするために、アプリケーションのpackage.jsonにある"build"スクリプトを拡張して、SSRビルドを作成することをお勧めします。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]
}

最後に、SSRサーバの構築と起動のため、以下のコマンドを実行してください。Then, to build and start the SSR server, you may run the following commands:

npm run build
node bootstrap/ssr/ssr.js

SSRをInertiaで使用している場合、代わりにinertia:start-ssr Artisanコマンドを使用してSSRサーバを起動してください。If you are using SSR with Inertia[https://inertiajs.com/server-side-rendering], you may instead use the inertia:start-ssr Artisan command to start the SSR server:

php artisan inertia:start-ssr

lightbulb Note: Laravelのスターターキットには、すでに適切なLaravel、Inertia SSR、Viteの構成が含まれています。Laravel、Inertia SSR、Viteを最速で使い始めるため、Laravel Breeze をチェックしてください。[!NOTE]
Laravel's starter kits[/docs/{{version}}/starter-kits] already include the proper Laravel, Inertia SSR, and Vite configuration. Check out Laravel Breeze[/docs/{{version}}/starter-kits#breeze-and-inertia] for the fastest way to get started with Laravel, Inertia SSR, and Vite.

Scriptとstyleタグ属性Script and Style Tag Attributes

コンテンツセキュリティポリシー(CSP)ノンスContent Security Policy (CSP) Nonce

コンテンツセキュリティポリシーの一環として、スクリプトやスタイルタグに、nonce属性を含めたい場合は、カスタムミドルウェアuseCspNonceメソッドを使用して、ノンスを生成・指定できます。If you wish to include a nonce attribute[https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce] on your script and style tags as part of your Content Security Policy[https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP], you may generate or specify a nonce using the useCspNonce method within a custom middleware[/docs/{{version}}/middleware]:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Vite;
use Symfony\Component\HttpFoundation\Response;

class AddContentSecurityPolicyHeaders
{
    /**
     * 受診リクエストの処理
     *
     * @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は生成するすべてのscriptタグとstyleタグへ、nonce属性を自動的に含めます。After invoking the useCspNonce method, Laravel will automatically include the nonce attributes on all generated script and style tags.

Laravelのスターターキットに含まれるZiggy @route directiveなど、別の場所でノンスを指定する必要がある場合、cspNonceメソッドを使用して取得できます。If you need to specify the nonce elsewhere, including the Ziggy @route directive[https://github.com/tighten/ziggy#using-routes-with-a-content-security-policy] included with Laravel's starter kits[/docs/{{version}}/starter-kits], you may retrieve it using the cspNonce method:

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

Laravelに使わせたいノンスが既にある場合は、useCspNonceメソッドへ、そのノンスを渡してください。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);

サブリソース完全性(SRI)Subresource Integrity (SRI)

Viteマニフェストにアセット用のintegrityハッシュが含まれている場合、Laravelは自動的にintegrity属性を生成するスクリプトとスタイルタグに追加し、サブリソース完全性を強要します。Viteはデフォルトでは、integrityハッシュをマニフェストに含みませんが、 vite-plugin-manifest-sri NPMプラグインをインストールすれば、これを有効にできます。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[https://developer.mozilla.org/en-US/docs/Web/Security/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[https://www.npmjs.com/package/vite-plugin-manifest-sri] NPM plugin:

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

このプラグインは、vite.config.jsファイルで有効にします。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');

この自動検出を完全に無効にする場合は、useIntegrityKeyメソッドへfalseを渡します。If you would like to disable this auto-detection completely, you may pass false to the useIntegrityKey method:

Vite::useIntegrityKey(false);

任意の属性Arbitrary Attributes

もし、スクリプトタグやスタイルタグに追加の属性、例えば data-turbo-track属性を含める必要がある場合は、useScriptTagAttributesuseStyleTagAttributesメソッドで指定できます。通常、このメソッドは サービスプロバイダから呼び出す必要があります。If you need to include additional attributes on your script and style tags, such as the data-turbo-track[https://turbo.hotwired.dev/handbook/drive#reloading-when-assets-change] attribute, you may specify them via the useScriptTagAttributes and useStyleTagAttributes methods. Typically, this methods should be invoked from a service provider[/docs/{{version}}/providers]:

use Illuminate\Support\Facades\Vite;

Vite::useScriptTagAttributes([
    'data-turbo-track' => 'reload', // 属性の値を指定
    'async' => true, // 値を指定しない属性
    'integrity' => false, // 本来含まれる属性を除外
]);

Vite::useStyleTagAttributes([
    'data-turbo-track' => 'reload',
]);

条件付きで属性を追加する必要がある場合、アセットのソースパスとそのURL、マニフェストのチャンク、およびマニフェスト全体を受け取るコールバックを渡してください。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 Warning! Vite開発サーバが起動している間は、$chunk$manifest引数は、nullになります。[!WARNING]
The $chunk and $manifest arguments will be null while the Vite development server is running.

高度なカスタマイズAdvanced Customization

LaravelのViteプラグインは、ほとんどのアプリケーションで動作するように、合理的な規約をはじめから使用しています。しかし、時にはViteの動作をカスタマイズする必要が起きるかもしれません。追加のカスタマイズオプションを有効にするための、@vite Bladeディレクティブの代わりに使用可能な、以下のメソッドとオプションを提供しています。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')) // 「ホット」なファイルのカスタマイズ
            ->useBuildDirectory('bundle') // ビルドディレクトリのカスタマイズ
            ->useManifestFilename('assets.json') // マニフェストファイル名のカスタマイズ
            ->withEntryPoints(['resources/js/app.js']) // エントリポイントの指定
            ->createAssetPathsUsing(function (string $path, ?bool $secure) { // Customize the backend path generation for built assets...
                return "https://cdn.example.com/{$path}";
            })
    }}
</head>

そして、vite.config.jsファイル内でも、同じ設定を指定する必要があります。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', // 「ホット」なファイルのカスタマイズ
            buildDirectory: 'bundle', // ビルドディレクトリのカスタマイズ
            input: ['resources/js/app.js'], // エントリポイントの指定
        }),
    ],
    build: {
      manifest: 'assets.json', // マニフェストファイル名のカスタマイズ
    },
});

開発サーバURLの修正Correcting Dev Server URLs

Viteエコシステム内のプラグインのいくつかは、フォワードスラッシュで始まるURLを常にVite開発サーバを指すと仮定しています。しかし、Laravelとの統合の関係上、これは好ましくありません。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.

例えば、vite-imagetoolsプラグインは、Viteがあなたのリソースを提供しているとき、以下のようなURLを出力します。For example, the vite-imagetools plugin outputs URLs like the following while Vite is serving your assets:

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

vite-imagetoolsプラグインは、出力するURLがViteによりインターセプトされ、そのプラグインが/@imagetools から始まるすべてのURLを処理することを期待しています。このような挙動を期待するプラグインを使用している場合、手作業でURLを修正する必要があります。これは、vite.config.jsファイルのtransformOnServeオプションを使用して実現できます。この例は、生成されたコード内における/@imagetoolsの全出現箇所で、開発サーバのURLを前へ追加します。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 behaviour, you will need to manually correct the URLs. You can do this in your vite.config.js file by using the transformOnServe option.

この例では、生成したコード内で、/@imagetoolsのすべての出現の前に開発サーバのURLを追加しています。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(),
    ],
});

これで、Viteがアセットを配信する間、Viteの開発サーバを指すURLが出力されます。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] -->

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作