Building and Deploying Code-Behind

How code-behind modules get from Counter.razor.js to the browser: how they are published and cached, what happens when you deploy while pages are open, how they work with a Content Security Policy, and how to write them in TypeScript, use npm packages and test them.

Publishing and URLs

A .razor.js file next to a component is a static web asset: the .NET SDK serves it in development and copies it into wwwroot when you publish. Its URL is its path in the project, so Features/Home/Counter.razor.js is served at /Features/Home/Counter.razor.js. In a Razor class library it is under the library's base path, for example /_content/MyLibrary/Counter.razor.js. A request path base (UsePathBase) is added automatically.

By default the file is published exactly as written: no bundling, no minification, no transpiling. The build pipeline below is optional.

Caching and fingerprinted URLs

With app.MapStaticAssets(), every static asset also gets a fingerprinted URL that contains a hash of its content (Counter.ezjsubrzj2.razor.js) and is served with Cache-Control: max-age=31536000, immutable. RzAlpineComponent renders that URL when it is available, so browsers download a module once and fetch it again only when it changes. The plain URL is served with no-cache, which makes the browser check it on every page load.

  • Razor component endpoints (MapRazorComponents) resolve fingerprints automatically.
  • Controllers and Razor Pages: add .WithStaticAssets() (app.MapControllers().WithStaticAssets()). The RizzyUI starter does this.
  • htmx fragments from minimal APIs use the same fingerprinted URLs as full pages, so a swapped component shares the module the page already loaded.
  • Without MapStaticAssets() (only UseStaticFiles(), or a static export), the plain URL is used. Everything works; caching just depends on revalidation.
Program.cs
app.UseStaticFiles();      // physical files under wwwroot
app.UseRouting();
// ...
app.MapStaticAssets();     // fingerprinted URLs with long-lived caching
app.MapControllers().WithStaticAssets();

Deploying while pages are open

With htmx, a page can stay open for hours and keep receiving fragments from the server, including after you deploy a new version. Two things protect it:

  • New markup loads the new module. The generated x-data name includes a hash of the module's URL, and the fingerprinted URL changes when the module changes. A fragment from the new version therefore uses a new name and loads the new module, instead of running the old module (already loaded under the old name) against new markup. If you set Name yourself, you lose this.
  • Old markup survives a missing file. If a fingerprinted file from the previous version is gone (a lazily loaded component on an old page), RizzyUI retries once with the plain URL and logs a warning.

If neither works, RizzyUI logs the failure once and dispatches rz:module-error on document. A page can use it to suggest a reload:

site.js
document.addEventListener('rz:module-error', (event) => {
  // event.detail: { name, url, fallbackUrl, error }
  Rizzy.toast.warning('A newer version of this page is available. Reload to continue.');
});

Where possible, keep the previous release's static files available for a while after a deployment (a CDN or blob storage that does not delete old files does this).

Preloading

Components with the default eager load strategy also render <link rel="modulepreload"> for their module, once per request, so the browser downloads it while it reads the page instead of after Alpine has started. Lazy strategies (visible, idle, media, event) do not preload. Turn it off with Preload="false".

Content Security Policy

  • Code-behind components render no inline scripts. Props are in a data-rz-props attribute; the module is loaded with a dynamic import().
  • With script-src 'self', same-origin modules are allowed. With 'nonce-…' 'strict-dynamic', modules imported by RizzyUI's (nonced) script are allowed too.
  • Serving static files from a CDN on another origin: add that origin to script-src, and the CDN must send CORS headers, because modules are fetched in CORS mode.
  • Modules work with both rizzyui.js and the CSP build rizzyui-csp.js. With the CSP build, expressions in your markup must follow its rules (no assignments in attributes); logic in the module is ordinary JavaScript.

Minification and bundling

Compression (gzip and Brotli, generated at publish) already removes most of the size of small modules, so RizzyUI does not minify them by default. If your own build, a CDN's "auto minify" or a static site generator rewrites them, it must:

  • Not rename properties. The markup calls methods and reads state by name (x-on:click="increment"). Renaming local variables is fine; property mangling is not.
  • Keep the module an ES module with its default export. Do not wrap it in an IIFE or convert it to CommonJS.
  • Keep methods as methods. Converting them to arrow functions breaks this.
  • Handle modern syntax. A minifier that does not understand template literals can cut a file short (this happened to RizzyUI's own static docs site).
  • Not change files that have integrity hashes, or must update the hashes.

Do not combine all code-behind modules into one file: each module loads only on pages that use it, and is cached separately. Bundling one module with the files it imports is useful, and is what the build pipeline does.

TypeScript and npm imports: the build pipeline

Opt in with one property, and install esbuild in the project (it needs Node.js, like the Tailwind build):

MyApp.csproj
<PropertyGroup>
  <RizzyUICodeBehindBuild>esbuild</RizzyUICodeBehindBuild>
</PropertyGroup>
Terminal
npm install --save-dev esbuild

Each Component.razor.ts and Component.razor.js is then built on every dotnet build: esbuild bundles it with the files and npm packages it imports, removes TypeScript types and writes Component.razor.js under obj/rizzyui-codebehind/. That file replaces the source as the static web asset, so URLs, fingerprints, compression and publishing are unchanged. dotnet watch rebuilds when a .razor.ts file changes.

Counter.razor.ts
import type { AlpineCodeBehind } from 'rizzyui';
import { formatCount } from './formatting';   // bundled into the module

interface Props { InitialCount: number }

const counter: AlpineCodeBehind<Props> = () => ({
  count: 0,
  init() { this.count = this.$props.InitialCount; },
  get label() { return formatCount(this.count); },
  increment() { this.count++; },
});

export default counter;
PropertyDefaultMeaning
RizzyUICodeBehindBuildnoneesbuild turns the pipeline on.
RizzyUICodeBehindMinifytrue in ReleaseRemoves whitespace and simplifies syntax. Property names are never changed.
RizzyUICodeBehindSourceMapinline outside ReleaseSource maps so the browser shows your original file; false to turn off.
RizzyUICodeBehindTargetes2020The JavaScript version esbuild writes.
RizzyUIEsbuildCommandnpx --no-install esbuildThe command that runs esbuild, for an esbuild installed elsewhere.
  • esbuild removes types without checking them. Run npx tsc --noEmit (with a tsconfig.json that maps rizzyui like the starter's jsconfig.json) in CI to type-check.
  • A component has one module: Counter.razor.ts and Counter.razor.js together are an error (RZUI1002).
  • The RizzyUI runtime is not imported: use the Rizzy global and Alpine's magics. import type from rizzyui is removed at build time.

Imports between modules without the pipeline

Without the build pipeline, a module can import other modules by URL. Only *.razor.js files next to components are served, so put shared code under wwwroot (import { format } from '/js/format.js'). Such imports use the plain URL; to have them use fingerprinted URLs too, add an import map to the layout's <head>, before any module script. It lists every static asset, so it adds to every page's size.

App.razor
<ImportMap nonce="@Nonce" />

Static site export

A static site generator must copy every module route, plain and fingerprinted, byte for byte. The static web assets endpoints manifest in the build output (MyApp.staticwebassets.endpoints.json) lists them: the RizzyUI documentation site adds every route ending in .razor.js from it, and copies scripts without rewriting them.

Testing modules

The npm package @jalexsocial/rizzyui includes a helper that mounts a module the way RzAlpineComponent renders it, with Alpine and $props, so its logic can be tested in Node. It resolves after init() and, if the module has one, ready(). It needs a DOM, for example happy-dom:

Counter.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import { GlobalRegistrator } from '@happy-dom/global-registrator';
GlobalRegistrator.register();

const { mountCodeBehind } = await import('@jalexsocial/rizzyui/testing');
const { default: counter } = await import('../Features/Home/Counter.razor.js');

test('increments from the initial count', async () => {
  const { data, root, nextTick } = await mountCodeBehind(counter, {
    props: { InitialCount: 10 },
    html: '<span x-text="count"></span>',
  });
  data.increment();
  await nextTick();
  assert.equal(root.querySelector('span').textContent, '11');
});