Loader#

Vite Asset Loader.

This module provides the ViteAssetLoader class for loading and rendering Vite-managed assets. The loader handles both development mode (with HMR) and production mode (with manifest-based asset resolution).

Key features: - Async initialization for non-blocking I/O during app startup - Manifest parsing for production asset resolution - HMR client script generation for development - React Fast Refresh support

litestar_vite.loader.render_hmr_client(context: Mapping[str, Any], /) markupsafe.Markup[source]#

Render the HMR client script tag.

This is a Jinja2 template callable that renders the Vite HMR client script tag for development mode.

Parameters:

context – The template context containing the request.

Returns:

HTML markup for the HMR client script, or empty markup if VitePlugin is not registered.

litestar_vite.loader.render_asset_tag(context: Mapping[str, Any], /, path: str | list[str], scripts_attrs: dict[str, str] | None = None) markupsafe.Markup[source]#

Render asset tags for the specified path(s).

This is a Jinja2 template callable that renders script/link tags for Vite-managed assets. Also works for HTMX partial responses.

Parameters:
  • context – The template context containing the request.

  • path – Single path or list of paths to assets.

  • scripts_attrs – Optional attributes for script tags.

Returns:

HTML markup for the asset tags, or empty markup if VitePlugin is not registered.

Example

In a Jinja2 template: {{ vite_asset(“src/main.ts”) }} {{ vite_asset(“src/components/UserProfile.tsx”) }}

litestar_vite.loader.render_static_asset(context: Mapping[str, Any], /, path: str) str[source]#

Render a static asset URL.

This is a Jinja2 template callable that returns the URL for a static asset.

Parameters:
  • context – The template context containing the request.

  • path – Path to the static asset.

Returns:

The full URL to the static asset, or empty string if VitePlugin is not registered.

litestar_vite.loader.render_routes(context: Mapping[str, Any], /, *, only: list[str] | None = None, exclude: list[str] | None = None, include_components: bool = False) markupsafe.Markup[source]#

Render inline script tag with route definitions.

This is a Jinja2 template callable that renders an inline script tag containing route metadata for client-side type-safe routing.

The script defines a global window.Litestar.routes object that can be used by frontend routers.

Uses Litestar’s built-in serializers, picking up any custom type encoders configured on the app.

Parameters:
  • context – The template context containing the request.

  • only – Optional list of route patterns to include.

  • exclude – Optional list of route patterns to exclude.

  • include_components – Include Inertia component names.

Returns:

HTML markup for the inline routes script containing route metadata as a JSON object.

Example

In a Jinja2 template: {{ vite_routes() }} {{ vite_routes(exclude=[‘/api/internal’]) }}

class litestar_vite.loader.ViteAssetLoader[source]#

Bases: object

Vite asset loader for managing frontend assets.

This class handles loading and rendering of Vite-managed assets. It supports both development mode (with HMR) and production mode (with manifest-based asset resolution).

The loader is designed to be instantiated per-app (not a singleton) and supports async initialization for non-blocking file I/O.

config#

The Vite configuration.

Example

loader = ViteAssetLoader(config) await loader.initialize() html = loader.render_asset_tag(“src/main.ts”)

__init__(config: ViteConfig) None[source]#

Initialize the asset loader.

Parameters:

config – The Vite configuration.

async resolve_html_entry(entry: str, *, production_path: Path | str, absolute_dev_asset_urls: bool = False) str[source]#

Resolve an exact Vite HTML entry from development or production.

resolve_html_entry_sync(entry: str, *, production_path: Path | str, absolute_dev_asset_urls: bool = False) str[source]#

Synchronously resolve an exact Vite HTML entry.

classmethod initialize_loader(config: ViteConfig) ViteAssetLoader[source]#

Synchronously initialize a loader instance.

This is a convenience method for synchronous initialization. For async contexts, prefer using initialize() after construction.

Parameters:

config – The Vite configuration.

Returns:

An initialized ViteAssetLoader instance.

async initialize() None[source]#

Asynchronously initialize the loader.

This method performs async file I/O to load the manifest or hot file. Call this during app startup in an async context.

parse_manifest() None[source]#

Synchronously parse the Vite manifest file.

This method reads the manifest.json file in production mode or the hot file in development mode.

Note: For async contexts, use initialize() instead.

property manifest_content: str#

Get the raw manifest content.

Returns:

The raw JSON string content of the Vite manifest file.

property manifest: dict[str, Any]#

The parsed Vite manifest.

Returns:

The parsed manifest dict, or an empty dict in hot-dev mode or before initialization.

property version_id: str#

Get the version ID of the manifest.

The version ID is used for cache busting and Inertia.js asset versioning.

Returns:

A hash of the manifest content, or “1.0” if no manifest.

render_hmr_client() Markup[source]#

Render the HMR client script tags.

Returns:

HTML markup containing React HMR and Vite client script tags.

render_asset_tag(path: str | list[str], scripts_attrs: dict[str, str] | None = None) Markup[source]#

Render asset tags for the specified path(s).

Parameters:
  • path – Single path or list of paths to assets.

  • scripts_attrs – Optional attributes for script tags.

Returns:

HTML markup for script and link tags.

get_static_asset(path: str) str[source]#

Get the URL for a static asset.

Parameters:

path – The path to the asset.

Returns:

The full URL to the asset.

Raises:

AssetNotFoundError – If the asset is not in the manifest.

generate_ws_client_tags() str[source]#

Generate the Vite HMR client script tag.

Only generates output in development mode with hot reload enabled.

Returns:

Script tag HTML or empty string in production.

generate_react_hmr_tags() str[source]#

Generate React Fast Refresh preamble script.

Only generates output when React mode is enabled in development.

Returns:

React refresh script HTML or empty string.

generate_asset_tags(path: str | list[str], scripts_attrs: dict[str, str] | None = None) str[source]#

Generate all asset tags for the specified file(s).

Parameters:
  • path – Path or list of paths to assets.

  • scripts_attrs – Optional attributes for script tags.

Returns:

HTML string with all necessary script and link tags.

Raises:

ImproperlyConfiguredException – If asset not found in manifest.

Secondary HTML entries#

ViteAssetLoader.resolve_html_entry() resolves a nested Vite HTML entry without relying on Vite’s SPA fallback. Pass the source entry separately from the production artifact:

html = await plugin.asset_loader.resolve_html_entry(
    "pages/offline.html",
    production_path="public/offline.html",
    absolute_dev_asset_urls=True,
)

Relative production_path values are resolved beneath ViteConfig.root_dir. In production, or when the hot file is missing, empty, unreadable, or malformed, the production file is returned unchanged. When the current hot file contains an HTTP or HTTPS target, the loader asks that Vite server to read and transform the exact entry. Connection failures and non-success responses raise HTMLEntryResolutionError and do not fall back to a stale production artifact.

resolve_html_entry_sync() provides the same source selection and validation for synchronous callers. It performs blocking filesystem and network I/O, so do not call it on an async event-loop thread. Both methods create a bounded one-shot HTTP client outside plugin lifespan; the async method reuses the plugin’s lifespan-managed client when available.

Set absolute_dev_asset_urls=True when the returned document will be displayed outside the normal Litestar origin, including a document opened through a file:// URL. Only Vite module scripts, stylesheet and module-preload links, HMR paths, and React refresh imports are made absolute. Forms, images, anchors, unrelated links, and URLs that are already absolute are preserved. The browser-facing origin comes from .litestar.json.appUrl when available and otherwise from the hot file.

The Python litestar-vite package and npm litestar-vite-plugin package must use matching minor versions because the exact-entry request is a paired server contract. Version 0.30.x requires 0.30.x on both sides.