Vite

Vite+ asset headers and development server integration for FastHTML

Import add_vite and vite_headers explicitly from fasthtml.vite rather than fasthtml.common.

from fasthtml.vite import add_vite, vite_headers

Configuring an app

add_vite wires a Vite+ project under <directory>/<dirname> into a FastHTML app.

app = FastHTML()
add_vite(app, directory='.')

In production mode (dev=False), add_vite mounts <dirname>/dist at /<dirname> with StaticImmutable and prepends the asset tags from .vite/manifest.json to app.hdrs on startup. Pass build=True to run vp run build before loading the manifest.

In development mode (dev=True), add_vite runs vp dev inside the app lifespan on 127.0.0.1:<port>, waits up to 10 seconds for the server to listen, injects /@vite/client and /src/<entry_file> scripts for hot module replacement, and terminates the process on shutdown.

add_vite

def add_vite(
    app:fasthtml.core.FastHTML, # FastHTML application to configure
    entry_file:str='index.js', # Entry filename under `<dirname>/src/`
    dirname:str='frontend', # Subdirectory holding the Vite project, also used as URL prefix
    directory:str='.', # Base directory containing `dirname`
    dev:bool=False, # Own a localhost `vp dev` server with hot module replacement
    port:int=5173, # Port for the `vp dev` server when `dev=True`
    build:bool=False, # Run `vp run build` on startup before loading the manifest
):

Configure a FastHTML app to serve Vite+ assets or own a localhost vp dev server.

Reading manifest tags manually

Use vite_headers directly when you manage static serving yourself and only need the stylesheet, entry script, and modulepreload tags from .vite/manifest.json.

hdrs = vite_headers('frontend/dist', entry='src/index.js', base='/frontend/')

vite_headers

def vite_headers(
    outdir, # Build directory containing `.vite/manifest.json`
    entry:str='src/index.js', # Entry key in the Vite manifest
    base:str='/', # Public URL prefix, matching Vite's build `base`
):

Read a Vite manifest and return its stylesheets, entry script, and module preloads.