Skip to content

Asset Bundling (Vite)

Frontend

Asset Bundling (Vite)

Introduction

Vite is a frontend build tool. Browsers can't run TypeScript, JSX, or Tailwind CSS as you write them, so something has to turn your source files into plain JavaScript and CSS. While you develop, Vite does that on the fly and updates your open pages as you save. For production, Vite bundles your assets into files whose names change whenever their contents do, so a visitor's browser never holds on to a stale copy.

New applications come with Vite set up for React, TypeScript, Tailwind CSS, and Inertia. Your scripts live in resources/js, your styles live in resources/css, and vite.config.ts configures Laravel's Vite plugin. Laravel reads what Vite builds, so your views load the right files in development and in production without any changes.

Running Vite

While you work on your application, run laravel dev. It starts Vite's development server alongside your application, and Vite watches the resources directory, so your edits to scripts and styles appear in the browser right away. Laravel also reloads the page when you save a view or when your application restarts with new code. To learn more, check out the installation guide's section on running the application. If you'd rather run Vite on its own, run npm run dev:vite.

Before you deploy, build your assets for production:

1npm run build
1npm run build

Vite writes the build to public/build. The build includes a manifest that maps each source file, such as resources/js/app.tsx, to its versioned copy, and Laravel reads the manifest when your views load assets. Outside debug mode, Laravel reads the manifest only once, so restart your application after you rebuild.

Loading your scripts and styles

Vite builds your assets from entry points, which are the files your pages load directly. Each entry point imports the rest of your scripts and styles. New applications have two entry points, listed in the plugin's input option in vite.config.ts:

1laravel({
2 input: ['resources/css/app.css', 'resources/js/app.tsx'],
3}),
1laravel({
2 input: ['resources/css/app.css', 'resources/js/app.tsx'],
3}),

To load the entry points on a page, call vite in the <head> of your layout. While the development server runs, vite writes <script> and <link> tags that point to the server. Otherwise, the tags point to your build, and they include the CSS that each script imports:

1<!-- resources/views/layout.html -->
2 
3<!DOCTYPE html>
4<html lang="en">
5 <head>
6 {{head}}
7 {{viteReactRefresh}}
8 {{vite "resources/css/app.css" "resources/js/app.tsx"}}
9 </head>
10 <body>
11 {{block "content" .}}{{end}}
12 </body>
13</html>
1<!-- resources/views/layout.html -->
2 
3<!DOCTYPE html>
4<html lang="en">
5 <head>
6 {{head}}
7 {{viteReactRefresh}}
8 {{vite "resources/css/app.css" "resources/js/app.tsx"}}
9 </head>
10 <body>
11 {{block "content" .}}{{end}}
12 </body>
13</html>

viteReactRefresh turns on React Fast Refresh, which updates a component in place without losing its state. It only writes a script while the development server runs, and it must come before vite. If you don't use React, leave it out. If your application uses Inertia, its root view loads your scripts with these same two helpers.

Until you run npm run build or start the development server, vite writes an HTML comment in place of the tags and logs a warning. If a page shows up with no styles, check whether you've built your assets yet.

Processing static assets

Your images and fonts change from time to time, too, and a versioned name lets browsers cache each version for good. Vite versions every file that your scripts, styles, or views refer to through Vite. A file in public that you link by its absolute path, such as /favicon.ico, skips Vite, and Laravel serves the file as it is.

In JavaScript and CSS

When you import an image in a script, or refer to an image by a relative path in CSS, Vite puts a versioned copy in the build. For example, a page component might import the Laravel logo from resources/images:

1import laravel from '../../images/laravel.svg';
2 
3export default function Welcome() {
4 return <img src={laravel} alt="Laravel" />;
5}
1import laravel from '../../images/laravel.svg';
2 
3export default function Welcome() {
4 return <img src={laravel} alt="Laravel" />;
5}

A relative path starts from the file that contains it, so ../../images in a file in resources/js/pages points to resources/images.

In views

Your views may need versioned files too, such as a logo in your layout. A view can't import a file the way a script does, so tell Vite which files your views use with the plugin's assets option:

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

The next npm run build versions those files. In a view, viteAsset returns a file's URL, given the file's path in your application:

1<img src="{{viteAsset "resources/images/logo.png"}}" alt="Acme">
1<img src="{{viteAsset "resources/images/logo.png"}}" alt="Acme">

While the development server runs, viteAsset returns the server's URL for the file. If the build doesn't have the file, such as a file outside assets or one you added since your last build, the render fails with an error that names the file. viteAsset doesn't need a request, so it also works in mail views and in views that jobs render.

Environment variables

Your scripts sometimes need a setting from your environment, such as the public key of an error tracker. Vite reads your .env file too, and passes the variables whose names start with VITE_ to your scripts:

1VITE_SENTRY_DSN=https://[email protected]/7
1VITE_SENTRY_DSN=https://[email protected]/7

Your scripts read each variable from import.meta.env:

1const dsn = import.meta.env.VITE_SENTRY_DSN;
1const dsn = import.meta.env.VITE_SENTRY_DSN;

Every VITE_ variable ends up in the JavaScript that browsers download, so never put a secret in one.

Content Security Policy

A Content Security Policy tells the browser which scripts a page may run. For example, if an attacker slips a <script> tag into a comment or a profile, the browser refuses to run it. A strict policy allows only the tags that carry the response's nonce, a random value that changes with every request.

To give each request a nonce, write a middleware that makes one with rand.Text from crypto/rand, passes it to vite.WithCSPNonce, and allows the same nonce in the response's Content-Security-Policy header:

1package security
2 
3import (
4 "crypto/rand"
5 
6 "go.laravel.com/vite"
7 "go.laravel.com/web"
8)
9 
10// ContentSecurityPolicy lets each page run only the scripts that carry
11// the request's nonce.
12type ContentSecurityPolicy struct{}
13 
14func (ContentSecurityPolicy) Handle(r *web.Request, next web.Next) *web.Response {
15 nonce := rand.Text()
16 
17 res := next(r.WithContext(vite.WithCSPNonce(r.Context(), nonce)))
18 
19 return res.WithHeader(
20 "Content-Security-Policy",
21 "script-src 'nonce-"+nonce+"' 'strict-dynamic'; object-src 'none'; base-uri 'none'",
22 )
23}
1package security
2 
3import (
4 "crypto/rand"
5 
6 "go.laravel.com/vite"
7 "go.laravel.com/web"
8)
9 
10// ContentSecurityPolicy lets each page run only the scripts that carry
11// the request's nonce.
12type ContentSecurityPolicy struct{}
13 
14func (ContentSecurityPolicy) Handle(r *web.Request, next web.Next) *web.Response {
15 nonce := rand.Text()
16 
17 res := next(r.WithContext(vite.WithCSPNonce(r.Context(), nonce)))
18 
19 return res.WithHeader(
20 "Content-Security-Policy",
21 "script-src 'nonce-"+nonce+"' 'strict-dynamic'; object-src 'none'; base-uri 'none'",
22 )
23}

Then add security.ContentSecurityPolicy to your global middleware in the Middleware option of bootstrap/app.go:

1Middleware: func(m *laravel.Middleware, cfg *config.Config) {
2 m.Global.Append(security.ContentSecurityPolicy{})
3},
1Middleware: func(m *laravel.Middleware, cfg *config.Config) {
2 m.Global.Append(security.ContentSecurityPolicy{})
3},

The tags that vite and viteReactRefresh write now carry the nonce, as in <script type="module" src="/build/assets/app-4f2a.js" nonce="...">, so your pages and your Inertia root view keep loading their scripts. With 'strict-dynamic', the browser also runs the scripts that your entry points import.

A script you write in a view needs the nonce as well, such as a script in your layout that applies the visitor's dark theme before the page draws. cspNonce returns the request's nonce in any view:

1<script nonce="{{cspNonce}}">
2 document.documentElement.classList.toggle('dark', localStorage.theme === 'dark');
3</script>
1<script nonce="{{cspNonce}}">
2 document.documentElement.classList.toggle('dark', localStorage.theme === 'dark');
3</script>

In a handler or a middleware, vite.CSPNonce(r) returns the same nonce.

Subresource integrity

Subresource Integrity makes the browser check that each script and stylesheet it loads is the file your build made. If someone changes a copy of the file on a server or on its way to the browser, the browser refuses to run it. Vite's manifest doesn't hold the hashes that the browser checks, but the vite-plugin-manifest-sri plugin adds them. Install the plugin:

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

Then add the plugin to vite.config.ts:

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

After your next npm run build, each tag that vite writes carries its file's integrity attribute, as in <script type="module" src="/build/assets/app-4f2a.js" integrity="sha384-...">. While the development server runs, the tags have no integrity attribute, since the server's files change as you save.

Vite in tests

Your tests don't need a build of your assets. Without a build, vite writes its HTML comment and viteAsset returns an empty URL, so your pages still render and your assertions still see their content. Both helpers log a warning when that happens.

If you've built your assets, the helpers work as they do in production. So when a page's viteAsset path isn't in the build, the page fails to render in your test too, which catches a typo in the path before your visitors see a broken image.