最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Cant import scoped Javascript in Blazor Standalone WebAssembly - Stack Overflow

programmeradmin0浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论