3

In my project I have a Components folder with two files:

  • Board.razor
    • In this file I have <h1>Board component</h1>
  • Board.razor.js
    • In this file I simply have a console.log('test'); statement

In the Index.razor file I load my custom component:

<Board></Board>

When I run my application I see that my Board component loads successfully.

To my understanding the .js file should be automatically discovered and loaded by the Blazor application.

So my expectation is that I should also see a console.log message in the browsers console window. But this does not happen. It seems like my JS file is not loaded?

According to this github conversation support for this should be there: https://github.com/dotnet/sdk/pull/19270

Is there something I'm missing? Or is my expectation wrong?


Additional project info

I'm running a client side Blazor app on .NET 6.0, and I have the latest packages installed in my application:

<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.7" PrivateAssets="all" />

1 Answer 1

8

While it seems to be applicable to component level .css files it doesn't work for .js. You have to load those files explicitly -> https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-6.0#load-a-script-from-an-external-javascript-file-js-collocated-with-a-component

Below is an example that I have recently used.

In Component

  1. Have a couple of variables

     [Inject]
     private IJSRuntime JS { get; set; } = default!;
     private IJSObjectReference? _jsModule;
    
  2. Overload OnAfterRenderAsync method

     protected override async Task OnAfterRenderAsync(bool firstRender)
     {
         _jsModule ??= await JS.InvokeAsync<IJSObjectReference>(
             "import", "./Pages/Board.razor.js");
    
         await _jsModule.InvokeVoidAsync("loadBoardJS", parameters);
    
         await base.OnAfterRenderAsync(firstRender);
     }
    

Update your Board.razor.js file a little

export function loadBoardJS(parameters) {
...
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am trying to use this but I get the following error: "Error BLAZOR106 The JS module file 'G:\MyProject\Shared\MyComponent.razor.js' was defined but no associated razor component or view was found for it." However, the MyComponent.razor.js file shows under my MyComponent.razor file in the Solution Explorer. Any ideas what's wrong?
Fixed by marking component as Content instead of None.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.