Skip to content

Vite ​

Introduction ​

Plinth does not bundle your frontend itself. It integrates with Vite through two small packages that split the work in half:

  • @plinthjs/vite-plugin runs inside Vite. It configures the build, writes the build manifest where Plinth can find it, and announces the dev server.
  • @plinthjs/vite runs inside your application. It looks at what the plugin produced and turns your entry files into the right script and link tags for the page.

In development the tags point at the Vite dev server (with hot module replacement). In production they point at the hashed files from the build. The same call in your template works in both cases.

bash
pnpm add @plinthjs/vite
pnpm add -D @plinthjs/vite-plugin vite

vite is a peer dependency of the plugin (version 5 or 6).

Configuring Vite ​

Add the plugin to vite.config.ts and list your entry files. The frontend applications generated by create-plinthjs-app (the Vue and React stacks) come with this already set up.

ts
// vite.config.ts
import plinth from '@plinthjs/vite-plugin'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [
    plinth({
      input: ['src/resources/js/app.ts', 'src/resources/css/app.css'],
      refresh: true,
    }),
  ],
})

plinth() also accepts a single entry or a list of entries with no other options: plinth('src/resources/js/app.ts').

Run vite while developing and vite build for production.

What the Plugin Does ​

For a build, the plugin:

  • builds into public/build and empties that directory first;
  • turns on the Vite manifest and uses your entries as the Rollup inputs;
  • sets the public base to /build/ so asset URLs resolve under that path;
  • disables Vite's publicDir copying, so your public folder is not copied into the build;
  • copies the manifest that Vite 5 and later writes at public/build/.vite/manifest.json to public/build/manifest.json, the location @plinthjs/vite reads.

For the dev server, the plugin sets base to /, enables CORS so pages served by your app can load modules from the dev server, and writes the dev server URL to a hot file (public/hot) once the server is listening. The hot file is removed when the process exits or receives SIGINT, SIGTERM or SIGHUP.

Plugin Options ​

ts
import plinth, { type PlinthViteOptions } from '@plinthjs/vite-plugin'

const options: PlinthViteOptions = {
  input: 'src/resources/js/app.tsx', // required: a string or a list
  publicDirectory: 'public', // the web root (default 'public')
  buildDirectory: 'build', // sub-directory of the web root (default 'build')
  hotFile: 'public/hot', // default '<publicDirectory>/hot'
  refresh: ['src/resources/views/**', 'src/routes/**'], // true, a glob, a list of globs, or false
}

If you change publicDirectory, buildDirectory or hotFile, pass the same values to the Vite class in your application, otherwise the two halves look in different places.

Reloading on Server Changes ​

With refresh: true, a second plugin named plinth:refresh is added for the dev server. It sends a full page reload to the browser when a matching file is added or changed. Vite already hot-reloads your frontend modules; this covers files Vite does not know about, such as server-rendered templates. The default patterns are:

src/resources/views/**
src/resources/**/*.plinth
src/routes/**
src/controllers/**
src/middleware/**
src/models/**
src/providers/**
src/support/**
src/auth/**
resources/views/**
resources/**/*.plinth
routes/**

Patterns are simple globs (*, **, ?) matched against paths relative to the Vite root. Pass your own glob or list of globs to replace the defaults, or false (or omit the option) to turn the reload off.

Rendering Asset Tags ​

Create a Vite instance in your application and call tags with the same entries you gave the plugin. It returns an HTML string.

ts
import { Vite } from '@plinthjs/vite'

const vite = new Vite() // reads public/hot and public/build/manifest.json

vite.tags(['src/resources/js/app.ts', 'src/resources/css/app.css'])

After a production build, the result is a stylesheet tag for the entry's CSS, a modulepreload tag for each chunk the entry imports, and the entry script:

html
<link rel="stylesheet" href="/build/assets/app.9b2c.css" />
<link rel="modulepreload" href="/build/assets/vendor.1a2b.js" />
<script type="module" src="/build/assets/app.4f3a.js"></script>

While the dev server runs, the result is the Vite client plus one tag per entry, all served from the dev server. A CSS entry becomes a link tag and anything else a module script.

html
<script type="module" src="http://localhost:5173/@vite/client"></script>
<script type="module" src="http://localhost:5173/resources/js/app.ts"></script>
<link rel="stylesheet" href="http://localhost:5173/resources/css/app.css" />

tags also accepts a single string. Entry names must be the same strings you passed as input to the plugin.

Using It in a Template ​

There is no @vite directive in the template engine. Share the instance with your views and print the tags unescaped:

ts
import { ViewEngine } from '@plinthjs/view'

const views = new ViewEngine()
views.share({ vite })
views.register(
  'layout',
  '<head>{!! vite.tags(["src/resources/js/app.ts"]) !!}</head><body>@yield("content")</body>',
)

See Views for the {!! !!} syntax. The output is trusted HTML produced by the framework, which is why raw output is appropriate here.

Using It in a Controller ​

The Vue and React single-page stacks generated by create-plinthjs-app render a small HTML shell from the home controller. The shape is:

ts
import { Response } from '@plinthjs/http'
import { Vite } from '@plinthjs/vite'

import { join } from 'node:path'

const vite = new Vite({
  publicDirectory: join(process.cwd(), 'public'),
  buildDirectory: 'build',
  manifestFilename: 'manifest.json',
})

export function index(): Response {
  const head = `${vite.reactRefresh()}${vite.tags(['src/resources/js/app.tsx'])}`
  return Response.html(
    `<!doctype html><html><head>${head}</head><body><div id="app"></div></body></html>`,
  )
}

reactRefresh() returns the React Fast Refresh preamble while the dev server runs and an empty string in a production build. Skip it for Vue.

Hot Mode and Build Mode ​

vite.isRunningHot() is true when the hot file exists. It decides which kind of tags tags and asset produce. The dev server URL is the trimmed contents of the hot file, and http://localhost:5173 when the file is empty.

WARNING

If the dev server crashes without cleaning up, a stale public/hot file makes the application keep pointing at a server that is gone. Delete the file when that happens.

Asset URLs ​

asset(entry) resolves one entry to a single URL: the dev server URL in hot mode, the hashed file in build mode. This is useful for something like a preload link you write by hand.

ts
vite.asset('src/resources/js/app.ts') // => '/build/assets/app.4f3a.js'

To host built files on a CDN, set assetUrl. It is prepended to built URLs (but not to dev server URLs).

ts
const vite = new Vite({ assetUrl: 'https://cdn.example.com' })
vite.asset('src/resources/js/app.ts') // => 'https://cdn.example.com/build/assets/app.4f3a.js'

Reading the Manifest ​

manifest() returns the parsed manifest.json, cached after the first read. It throws Vite manifest not found at "public/build/manifest.json". Run the production build first. when the build has not run, and asking for an entry that is not in the manifest throws Entry "x" was not found in the Vite manifest.

ts
const manifest = vite.manifest()
manifest['src/resources/js/app.ts']?.file // => 'assets/app.4f3a.js'

content(entry) reads the built file itself, which lets you inline a small stylesheet into the page:

ts
const css = vite.content('src/resources/css/app.css')
const html = `<style>${css}</style>`

If you need to parse a manifest from somewhere else, parseManifest(json) turns a JSON string into a typed Manifest.

Options ​

Every path option is relative to the process working directory unless you pass an absolute path.

ts
const vite = new Vite({
  publicDirectory: 'public', // the web root (default 'public')
  buildDirectory: 'build', // build sub-directory (default 'build')
  manifestFilename: 'manifest.json', // default 'manifest.json'
  hotFile: 'public/hot', // default '<publicDirectory>/hot'
  assetUrl: 'https://cdn.example.com', // URL prefix for built assets (default same-origin)
})

You can also change them after construction. Each method returns the instance:

ts
vite
  .useBuildDirectory('admin-build')
  .useHotFile('public/admin.hot')
  .useManifestFilename('admin.json')

This is how one application serves two separately built frontends: build each with its own buildDirectory and hotFile in the plugin, and give each its own Vite instance.

Content Security Policy Nonce ​

useCspNonce() generates a random nonce, stores it, and returns it. Every tag from then on carries nonce="...". Send the same value in your Content-Security-Policy header.

ts
const nonce = vite.useCspNonce() // random
vite.useCspNonce('abc123') // or supply your own
vite.cspNonce() // => 'abc123'

The nonce is also applied to the reactRefresh() preamble. Call useCspNonce once per request, and use a per-request Vite instance or call it before rendering, since the nonce is stored on the instance and a nonce should not be reused across responses.

Subresource Integrity ​

When a build plugin writes an integrity hash into each manifest chunk, tags adds it as an integrity attribute on the matching tag. The manifest key it reads is integrity by default. Change it, or turn the feature off with false:

ts
vite.useIntegrityKey('sri')
vite.useIntegrityKey(false)

Integrity attributes are only emitted in build mode, because the dev server's files have no hashes. Plinth does not generate the hashes itself; they must come from the manifest.

Custom Tag Attributes ​

Add attributes to every script, stylesheet or preload tag with the three use...TagAttributes methods. A string value renders name="value", true renders a bare name, and false or null omits the attribute.

ts
vite.useScriptTagAttributes({ defer: true, 'data-turbo-track': 'reload' })
vite.useStyleTagAttributes({ media: 'screen' })
vite.usePreloadTagAttributes({ crossorigin: 'anonymous' })

Pass a function instead to compute attributes per tag. It receives src (the entry or chunk name), url (the resolved URL), and, in build mode, the chunk and the full manifest.

ts
vite.useStyleTagAttributes(({ src }) => ({ 'data-src': src }))

Testing ​

The Vite class reads files through a fileSystem option, so tests do not need a real build.

ts
const vite = new Vite({
  fileSystem: {
    exists: (path) => path === 'public/build/manifest.json',
    read: () =>
      JSON.stringify({ 'src/resources/js/app.ts': { file: 'assets/app.js', isEntry: true } }),
  },
})

vite.asset('src/resources/js/app.ts') // => '/build/assets/app.js'
vite.isRunningHot() // => false

Released under the MIT License.