Skip to content

Latest commit

 

History

History
109 lines (81 loc) · 5.6 KB

modules.md

File metadata and controls

109 lines (81 loc) · 5.6 KB

Runtime API modules

Astro docs: Modules

None of Astro's virtual modules can be imported into a .razor file, because it is compiled by Razor rather than Vite and has no ESM imports at all. The C# objects shadow them by name, so what you reach for follows from the module you would have imported.

Module In C#
astro:actions Write the action in C#; re-export astrosharp:actions. See Actions.
astro:content Write the loader in C#; read it back with Astro.Content.
astro:assets Astro.Assets for getImage(); <Image>, <Picture> and <Font> are generated .razor components over the real ones.
astro:env Astro.Env, against the same schema.
astro:i18n Astro.I18n; locale values on the Astro global.
astro:config Astro.Config — no wrapped functions; Site and Generator are on the global.
astro:middleware Implement IAstroMiddleware.
astro:transitions Astro.Transitions. <ClientRouter /> is imported with Astro.Import(..., export: "ClientRouter") — see View transitions.
astro:schema / astro/zod Schemas stay in content.config.ts; action inputs and loader entries are reflected from C#.
anything else Astro.Module("astro:whatever").

The escape hatch

The wrapped surfaces above are the functions worth reimplementing in C#. For anything else — a helper Astro adds after this was written, or one too niche to wrap — the module can be called directly.

Declare it once for the project, so Vite puts it in the build graph:

// src/lib/Modules.cs, or any .cs file in the project
[assembly: AstroModule("astro:i18n")]

Then use one of two forms, from any component:

@* Synchronous. Records the call and substitutes the result after the render, so it works inline
   in markup, where an <a href> cannot await. *@
<a href="@Astro.I18n.Defer("getRelativeLocaleUrl", "fr-FR", "about")">En français</a>

@code {
    private string? _url;

    // Asynchronous. Runs the call now and returns the real value, so C# can compute with it.
    protected override async Task OnInitializedAsync() =>
        _url = await Astro.I18n.CallAsync<string>("getRelativeLocaleUrl", "fr-FR", "about");
}

Both are on every module object, wrapped or not, so Astro.I18n.RelativeUrl(...) and Astro.I18n.Defer(...) sit side by side — the escape hatch is found by typing Astro.I18n. rather than by reading this page.

Values, not just functions

astro:assets exports imageConfig and fontData as plain values. Ask for one with no arguments and it is read rather than called:

var config = await Astro.Module("astro:assets").CallAsync<ImageConfig>("imageConfig");

Arguments are how the intent is read, so asking for a value with arguments is an error naming both facts rather than returning something plausible. A function that genuinely takes no arguments still works — it is called, because it is callable.

Defer versus CallAsync

Defer is for a value going straight into markup. It returns a DeferredValue, which is deliberately opaque — it has no members but ToString, so this does not compile:

if (Astro.I18n.Defer("getRelativeLocaleUrl", "fr", "about").StartsWith("/fr")) { }
//  error CS1929: 'DeferredValue' does not contain a definition for 'StartsWith'

That is on purpose. Until the render is over the value does not exist, only a token standing in for it, and code that branched on one would be quietly comparing the wrong string.

CallAsync gives you the real value, and is the only one of the two that works outside a render — a loader, endpoint, action or middleware has no HTML to substitute into, and takes IAstroModules from DI instead.

DeferHtml splices the result in unescaped, for a function that returns markup. Defer escapes as HTML text, which is correct both in a text node and in an attribute.

Limitations

The declaration cannot be avoided. Vite resolves imports statically, so a virtual module has to be imported by something in the build graph before it exists at all, and a .razor file has no imports to give. [AstroModule] makes the generated modules import it for real. It declares the module — it does not implement anything, so a function Astro ships tomorrow works the same day.

Declare it on the assembly, not on a component. [AstroModule] is accepted on a .razor file (@attribute [AstroModule("astro:i18n")]) and means exactly the same thing, which is the problem: the registry behind Defer and CallAsync is one per project. A per-file declaration reads as scoped and is not, so a component could call a module because some other file declared it, then break when that file was deleted.

A DeferredValue cannot be passed as a prop to an .astro component — props are serialized well before the substitution happens, so the token would be what arrived. A token that survives to the output fails the build rather than shipping as visible gibberish.

Neither form can reach paginate(), which is not importable and runs in GetStaticPaths before any render exists. That one stays StaticPathsContext.Paginate.

CallAsync needs a channel back to Astro, so it throws under serverRendering: 'wasm'. Defer works there, because the Node side resolves it after the render.