In the past I have already done this in InteractiveServer Blazor, which is to import {page}.razor.js
in my razor page through IJSRuntime
in the OnAfterRender
step of the page lifecycle. as follows:
Page.Razor.cs
public partial class Page : ComponentBase
{
[Parameter] public required IJSRuntime js { get; init; }
private IJSObjectReference pageModule;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
pageModule = js.InvokeAsync<IJSObjectReference>("import"
, "Components/Pages/Page.razor.js")
}
}
// dispose pattern hidden for simplicity
}
Page.razor.js
export function greet()
{
window.alert('!');
}
There is a way to make something similar work, by using global javascript files in wwwroot\*.js
and <script...
directives but that is not desired in the moment. I didn't find any way to use a modular aproach handled by the ComponentBase
object.
This is the web assembly startup implementation
Program.cs
using BlazorApp2;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
.NET Core 9 environment