vite-crystal v0.4.0

Clean, idiomatic, framework-agnostic Vite backend integration for Crystal.

vite-crystal

CI Docs License

Clean, idiomatic, framework-agnostic Vite backend integration for Crystal (>= 1.21.0).

vite-crystal has zero third-party runtime dependencies (Crystal stdlib only) and works with plain HTTP::Server + ECR, Kemal, Marten, Athena, or any custom Crystal HTTP stack.

Features

  • Vite 5–8 manifest support: Parses .vite/manifest.json including isEntry, isDynamicEntry, isWorker, isWorkerEntry, css, assets, and transitive imports.
  • Vite-recommended production tag ordering: Emits <link rel="stylesheet"> (entry + transitive imports), <script type="module"> (or <link rel="stylesheet"> for CSS-only entrypoints), and <link rel="modulepreload"> — deduplicated across multiple entrypoints and safe against circular import graphs.
  • Dev server & hot file auto-detection: Vite::Mode::Auto checks for public/hot dynamically (reading the dev server URL directly from it), or pin Vite::Mode::Development / Vite::Mode::Production.
  • React Fast Refresh support: Optional @vitejs/plugin-react preamble emitted before @vite/client in dev mode, or rendered standalone via react_refresh_tag.
  • Concurrency-safe by design: Manifest caching uses lock-free Atomic reads (:acquire/:release) under Fiber::ExecutionContext::Parallel, and reload! parses before acquiring the mutex so a failed reload preserves the live manifest.
  • Security & single-binary ready: Supports Subresource Integrity (integrity) hashes from plugins like vite-plugin-manifest-sri, embedded compile-time manifests (Client.new(manifest: ...)), manifest_hash (SHA-256), and RFC 8288 HTTP Link preload_headers.
  • Flexible ergonomics: Both a global Vite.configure / Vite.tags façade and instantiable Vite::Client.new for DI or multi-bundle setups, with IO-streaming overloads, CSP nonce, crossorigin, custom attributes, base_path, and CDN asset_host.

Installation

Add vite to your shard.yml:

dependencies:
  vite:
    github: spcbeck/vite-crystal
    version: ~> 0.4.0

Run shards install, then require "vite" in your application.

Vite Configuration

Configure Vite to emit .vite/manifest.json into your backend's public directory (e.g., public/build) and disable Vite's publicDir copying so your Crystal app owns public/.

[!IMPORTANT] Add "lib/" to server.watch.ignored in vite.config.js. Crystal's shards install creates symlinks inside lib/ that can cause Vite's file watcher to loop or crash if not ignored.

// vite.config.js
import { defineConfig } from "vite";

export default defineConfig({
  // Let your Crystal app own public/ rather than having Vite copy it into public/build
  publicDir: false,
  server: {
    // Allow your backend origin to load ESM modules from Vite in dev
    cors: {
      origin: "http://localhost:3000",
    },
    // Required in backend integration so assets referenced in JS/CSS resolve to Vite in dev
    origin: "http://localhost:5173",
    watch: {
      ignored: ["lib/"],
    },
  },
  build: {
    manifest: true,
    outDir: "public/build",
    rollupOptions: {
      input: ["src/main.ts"],
    },
  },
});

At the top of your frontend entrypoint (src/main.ts), import Vite's preload polyfill if your app uses code-splitting:

import "vite/modulepreload-polyfill";

Choosing Dev vs. Production Mode

There are two common ways to switch between dev and production:

  1. Explicit mode via ENV (simplest): Pin Vite::Mode::Development locally and Vite::Mode::Production in production. In Mode::Production, vite-crystal never checks the filesystem for a hot file.
  2. Automatic public/hot file (Vite::Mode::Auto, the default): When public/hot exists on disk, vite-crystal enters dev mode and reads the Vite dev server URL from that file; when it doesn't exist, it serves from .vite/manifest.json. You can wire this up with a tiny Vite plugin:
// Optional: auto-manage public/hot while `vite` dev server is running
import fs from "node:fs";
import path from "node:path";

function hotFilePlugin(hotPath = "public/hot") {
  return {
    name: "crystal-vite-hot",
    configureServer(server) {
      server.httpServer?.once("listening", () => {
        const addr = server.httpServer.address();
        const url =
          typeof addr === "object" && addr
            ? `http://localhost:${addr.port}`
            : "http://localhost:5173";
        fs.mkdirSync(path.dirname(hotPath), { recursive: true });
        fs.writeFileSync(hotPath, url);
      });
      const cleanup = () => fs.rmSync(hotPath, { force: true });
      process.once("exit", cleanup);
      process.once("SIGINT", () => { cleanup(); process.exit(); });
      process.once("SIGTERM", () => { cleanup(); process.exit(); });
    },
  };
}

Quick Start & What It Emits

require "vite"

Vite.configure do |config|
  config.mode = ENV["APP_ENV"]? == "production" ? Vite::Mode::Production : Vite::Mode::Development
  config.build_dir = "build"
  config.react = true
end

# Optional: fail fast on boot in production if the manifest is missing or invalid
Vite.load_manifest! unless Vite.dev?

Calling Vite.tags("src/main.tsx") emits:

In development (while running npx vite alongside your Crystal app):

<!-- Included when config.react = true -->
<script type="module">
import RefreshRuntime from "http://localhost:5173/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>
<script type="module" src="http://localhost:5173/@vite/client"></script>
<script type="module" src="http://localhost:5173/src/main.tsx"></script>

In production (after running npx vite build, resolved from public/build/.vite/manifest.json):

<link rel="stylesheet" href="/build/assets/main-5UjPuW-k.css">
<link rel="stylesheet" href="/build/assets/shared-ChJ_j-JJ.css">
<script type="module" src="/build/assets/main-BRBmoGS9.js"></script>
<link rel="modulepreload" href="/build/assets/shared-B7PI925R.js">

CSS-only entrypoints (e.g., Vite.tags("src/styles/app.css")) automatically emit <link rel="stylesheet"> in both dev and production rather than <script type="module">.

Common Patterns

Splitting <head> and <body> Tags (or Customizing Script vs. Link Attributes)

If you prefer stylesheets in <head> and scripts at the bottom of <body>, or want different attributes on <link> vs. <script> tags, compose the granular helpers instead of tags:

# Inside <head>
Vite.stylesheet_tags("src/main.tsx")

# Before </body>
Vite.react_refresh_tag
Vite.client_tag
Vite.script_tags("src/main.tsx", attributes: {"defer" => ""})
Vite.preload_tags("src/main.tsx")

In production, react_refresh_tag and client_tag return ""; in development, preload_tags returns "".

CSP Nonces, crossorigin, and Custom Attributes

Pass nonce, crossorigin, or arbitrary HTML attributes directly to tag helpers (empty string values render boolean attributes like defer):

Vite.tags(
  "src/main.tsx",
  nonce: request_nonce,
  crossorigin: "anonymous",
  attributes: {"data-turbo-track" => "reload"}
)

Static Assets & CDN Hosting

Use asset_path (raises Vite::EntryNotFoundError if missing) or asset_path? (returns nil if missing) for images, fonts, or optional assets referenced from server-side templates:

logo_url = Vite.asset_path("src/assets/logo.svg")
banner_url = Vite.asset_path?("src/assets/promo-banner.png")

If compiled assets are served from a CDN, set asset_host:

Vite.configure do |config|
  config.mode = Vite::Mode::Production
  config.build_dir = "build"
  config.asset_host = "https://cdn.example.com"
end

Vite.asset_path("src/assets/logo.svg")
# => "https://cdn.example.com/build/assets/logo-BuPIv-2h.svg"

Zero-Downtime Manifest Reload

Vite.reload! reads and validates the new manifest from disk before acquiring the mutex, so concurrent readers under Fiber::ExecutionContext::Parallel keep serving the previous valid manifest if a reload fails.

Subresource Integrity (SRI)

If your Vite build includes "integrity" hashes in .vite/manifest.json (e.g., via vite-plugin-manifest-sri), vite-crystal automatically emits integrity="..." attributes on production <link rel="stylesheet">, <script type="module">, and <link rel="modulepreload"> tags (config.integrity = false disables this).

Embedded Single-Binary Manifests, manifest_hash, and HTTP Link Headers

For single-binary deployments, embed .vite/manifest.json at compile time and pass it directly to Vite::Client.new or Vite.configure:

manifest = Vite::Manifest.from_json({{ read_file("public/build/.vite/manifest.json") }})

Vite.configure(manifest: manifest) do |config|
  config.mode = Vite::Mode::Production
end

# SHA-256 hex digest of the manifest (useful for Inertia.js asset versioning)
version = Vite.manifest_hash

# Emit an RFC 8288 Link header for 103 Early Hints / HTTP response preloading
if link = Vite.preload_header("src/main.tsx")
  context.response.headers["Link"] = link
end

Inlining Compiled Assets (content / content?) & Per-Tag Attributes

Inline compiled CSS or SVG assets directly from disk (guarded against path traversal outside <public_dir>/<build_dir>):

critical_css = Vite.content("src/styles/critical.css")
optional_svg = Vite.content?("src/assets/icon.svg")

Set default HTML attributes per tag type without affecting other tag types:

Vite.configure do |config|
  config.script_attributes = {"defer" => "", "data-turbo-track" => "reload"}
  config.style_attributes = {"media" => "screen"}
  config.preload_attributes = {"data-preload" => "true"}
end

Opt-in Dev Reverse-Proxy Middleware (require "vite/proxy")

If you prefer serving Vite dev assets and HMR WebSockets through your Crystal backend origin without CORS configuration, require "vite/proxy" and mount Vite::DevProxy. It forwards matching HTTP dev paths (/@vite/, /@react-refresh, /@fs/, /@id/, /node_modules/) as well as Vite HMR WebSocket upgrades (Sec-WebSocket-Protocol: vite-hmr), while passing unrelated app routes and WebSockets through:

require "http/server"
require "vite"
require "vite/proxy"

server = HTTP::Server.new([Vite::DevProxy.new]) do |context|
  context.response.content_type = "text/html; charset=utf-8"
  context.response.print(Vite.tags("src/main.ts"))
end

When proxying HMR WebSockets through your backend port (e.g., 3000), set server.hmr.clientPort: 3000 in vite.config.js so Vite's client connects to your backend origin.

Configuration Options

Property Default Description
mode Vite::Mode::Auto Auto checks hot_file dynamically; Development / Production pins the mode.
dev_server_url "http://localhost:5173" Fallback Vite dev server origin.
public_dir "public" Public web root used to resolve default hot and manifest paths.
build_dir "build" Output subdirectory inside public_dir and URL prefix in production.
manifest_path nil Explicit manifest path; defaults to <public_dir>/<build_dir>/.vite/manifest.json.
hot_file nil Explicit hot file path; defaults to <public_dir>/hot.
asset_host nil Optional CDN origin prepended to production URLs (e.g., "https://cdn.example.com").
base_path "" Optional Vite base subpath prefix for dev and prod URLs.
react false Automatically prepend the React Refresh preamble in dev tags calls.
preload true Emit <link rel="modulepreload"> tags for statically imported chunks in production.
integrity true Emit SRI integrity attributes in production when present in the manifest.
crossorigin nil Default crossorigin attribute (true, "anonymous", "use-credentials", or nil).
script_attributes nil Default HTML attributes merged onto <script type="module"> tags.
style_attributes nil Default HTML attributes merged onto <link rel="stylesheet"> tags.
preload_attributes nil Default HTML attributes merged onto <link rel="modulepreload"> tags.

API Overview

All helpers exist on both Vite (module façade) and Vite::Client (instance). Tag helpers return a String and provide an IO-streaming overload (io : IO, ...) to avoid intermediate string allocations:

  • tags(*entries, nonce: nil, preload: nil, react: nil, crossorigin: nil, attributes: nil)
  • client_tag(nonce: nil, crossorigin: nil, attributes: nil) (dev only)
  • react_refresh_tag(nonce: nil) (dev only)
  • stylesheet_tags(*entries, ...)
  • script_tags(*entries, ...)
  • preload_tags(*entries, ...) (prod only)
  • preload_header(*entries, crossorigin: nil) (prod only)
  • asset_path(entry) / asset_path?(entry)
  • content(entry) / content?(entry)
  • css_paths(*entries)
  • asset_paths(*entries)
  • load_manifest! / reload! / manifest / manifest_hash / dev? / dev_server_url
  • Vite::DevProxy (opt-in via require "vite/proxy")

Framework Integrations

Plain HTTP::Server + ECR

Plain HTTP::Server does not serve files from public/ on its own. In production (unless a reverse proxy like Nginx/Caddy sits in front), mount HTTP::StaticFileHandler so /build/assets/... requests resolve:

# src/server.cr
require "ecr"
require "http/server"
require "vite"

Vite.configure do |config|
  config.mode = ENV["APP_ENV"]? == "production" ? Vite::Mode::Production : Vite::Mode::Development
end

Vite.load_manifest! unless Vite.dev?

struct HomePage
  def initialize(@title : String, @nonce : String)
  end

  ECR.def_to_s "views/layout.ecr"
end

static_handler = HTTP::StaticFileHandler.new("public", directory_listing: false)
server = HTTP::Server.new([static_handler]) do |context|
  context.response.content_type = "text/html; charset=utf-8"
  HomePage.new("My App", "req-nonce-123").to_s(context.response)
end
server.bind_tcp(3000)
server.listen
<%# views/layout.ecr %>
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title><%= @title %></title>
    <%= Vite.tags("src/main.ts", nonce: @nonce) %>
    <%# Optional zero-allocation optimization: stream directly to ECR's internal IO buffer (`__str__`): %>
    <%# <% Vite.tags(__str__, "src/main.ts", nonce: @nonce) %> %>
  </head>
  <body>
    <img src="<%= Vite.asset_path("src/assets/logo.svg") %>" alt="Logo">
    <div id="app"></div>
  </body>
</html>

Kemal

Kemal serves ./public out of the box, so pointing Vite's build.outDir at public/build requires no extra static-file middleware:

# src/app.cr
require "kemal"
require "vite"

Vite.configure do |config|
  config.mode = Kemal.config.env == "production" ? Vite::Mode::Production : Vite::Mode::Development
  config.build_dir = "build"
end

Vite.load_manifest! unless Vite.dev?

get "/" do
  render "src/views/index.ecr", "src/views/layout.ecr"
end

Kemal.run
<%# src/views/layout.ecr %>
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <%= Vite.tags("src/main.ts", "src/styles/app.css") %>
  </head>
  <body><%= content %></body>
</html>

Run npx vite and crystal run src/app.cr in separate terminals during development; run npx vite build && KEMAL_ENV=production crystal run src/app.cr to test production locally.

Marten

In Marten, define and register a Marten::Template::Tag::Base subclass in an initializer (e.g., config/initializers/vite.cr). Tag::Base#render returns raw HTML directly into the template output without escaping:

# config/initializers/vite.cr
require "vite"

Vite.configure do |config|
  config.mode = Marten.env.production? ? Vite::Mode::Production : Vite::Mode::Development
  # If using Marten::Middleware::AssetServing (which serves from `assets.root` under `/assets/`),
  # point Vite's `outDir` to `assets/build` and set:
  # config.public_dir = Marten.settings.assets.root
  # config.base_path = Marten.settings.assets.url
  # config.build_dir = "build"
end

class ViteTag < Marten::Template::Tag::Base
  include Marten::Template::Tag::CanSplitSmartly

  def initialize(parser : Marten::Template::Parser, source : String)
    parts = split_smartly(source)
    raise Marten::Template::Errors::InvalidSyntax.new("vite tag requires at least one entry") if parts.size < 2

    @entry_expressions = parts[1..].map { |arg| Marten::Template::FilterExpression.new(arg) }
  end

  def render(context : Marten::Template::Context) : String
    entries = @entry_expressions.map { |expr| expr.resolve(context).to_s }
    Vite.tags(entries)
  end
end

Marten::Template::Tag.register("vite", ViteTag)
{# templates/base.html #}
<!doctype html>
<html>
  <head>
    {% vite "src/main.ts" %}
  </head>
  <body>{% block content %}{% endblock %}</body>
</html>

[!NOTE] Unlike Kemal, Marten does not serve ./public automatically — it serves collected assets from Marten.settings.assets.root at Marten.settings.assets.url when Marten::Middleware::AssetServing is enabled (or let Nginx/Caddy serve public/build in production).

Athena (DI-friendly)

Prefer instantiating Vite::Client directly instead of the global Vite module when using dependency injection, running isolated parallel tests, or serving multiple independent Vite builds from one binary.

In Athena::Framework, register a thin service with @[ADI::Register] and inject it into controllers (serving public/build via Nginx/Caddy or a static file listener in production):

require "athena"
require "mime"
require "vite"

@[ADI::Register]
class ViteAssets
  getter client : Vite::Client

  def initialize
    @client = Vite::Client.new do |config|
      config.mode = ENV["ATHENA_ENV"]? == "prod" ? Vite::Mode::Production : Vite::Mode::Development
      config.build_dir = "build"
    end
  end

  delegate tags, asset_path, to: @client
end

@[ADI::Register]
class HomeController < ATH::Controller
  def initialize(@vite : ViteAssets)
  end

  @[ARTA::Get("/")]
  def index : AHTTP::Response
    html = <<-HTML
      <!doctype html>
      <html>
        <head>#{@vite.tags("src/main.ts")}</head>
        <body><div id="app"></div></body>
      </html>
      HTML

    AHTTP::Response.new(
      html,
      headers: HTTP::Headers{"content-type" => MIME.from_extension(".html")}
    )
  end
end

ATH.run

Development

crystal tool format --check
crystal spec --order=random
crystal docs
ameba

Contributing

  1. Fork it (https://github.com/spcbeck/vite-crystal/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Run crystal tool format --check, crystal spec --order=random, and ameba
  4. Commit your changes (git commit -am 'feat: add some feature')
  5. Push to the branch (git push origin my-new-feature)
  6. Create a new Pull Request

License

MIT — see LICENSE.

Repository

vite-crystal

Owner
Statistic
  • 0
  • 0
  • 0
  • 0
  • 1
  • 11 minutes ago
  • December 6, 2026
License

MIT License

Links
Synced at

Sun, 06 Dec 2026 01:34:33 GMT

Languages