Unable to load the JavaScript module dynamically from a libarary using JavaScript Isolation ("Failed to fetch dynamically imported module" error)

4 hours ago 1
ARTICLE AD BOX

In How to share the JavaScript files for the Blazor via Nuget packages and include them to consuming projects? topics, I have been recomended to inject the JavaScript dependencies using via isolation:

@inject IJSRuntime JS @code { private IJSObjectReference? module; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { // Path: _content/[LibraryName]/[PathUnderWwwroot] module = await JS.InvokeAsync<IJSObjectReference>( "import", "./_content/MySharedLibrary/js/myScript.js"); } }

I even have created the following wrapper to isolate the magic strings from a library user:

public class JavaScriptFunctionality : IAsyncDisposable { private Microsoft.JSInterop.IJSObjectReference? MyLib; public static JavaScriptFunctionality GetNotInitializedYetInstance() { return new JavaScriptFunctionality(); } public async System.Threading.Tasks.Task Load( Microsoft.JSInterop.IJSRuntime javaScriptRuntime ) { this.MyLib = await javaScriptRuntime.InvokeAsync<Microsoft.JSInterop.IJSObjectReference>( "import", [ "./_content/MyCompany.MyLib/MyLib.js" ] ); } public async System.Threading.Tasks.Task<IValidatableControl.RootElementOffsetCoordinates> GetDOM_ElementOffsetCoordinates( Microsoft.AspNetCore.Components.ElementReference elementReference ) { return await this.getMyLib().InvokeAsync<IValidatableControl.RootElementOffsetCoordinates>("getDOM_ElementOffsetCoordinates", [ elementReference ]); } private Microsoft.JSInterop.IJSObjectReference getMyLib() { return this.MyLib ?? throw new Exception("Expected MyLib be initialized"); } async ValueTask IAsyncDisposable.DisposeAsync() { if (this.MyLibis not null) { await this.MyLib.DisposeAsync(); } } }

In a component, the usage is:

public partial class MyComponent: ComponentBase [Microsoft.AspNetCore.Components.Inject] protected Microsoft.JSInterop.IJSRuntime javaScriptRuntime { get; set; } = null!; private readonly JavaScriptFunctionality javaScriptFunctionality = JavaScriptFunctionality.GetNotInitializedYetInstance(); protected override async System.Threading.Tasks.Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { await this.javaScriptFunctionality.Load(this.javaScriptRuntime); } } }

I've confirmed that it works in test Blazor Standalone application in same solution as the library. But it does not work when library is been consuming by ".NET MAUI Blazor Hybrid and Web App" project. The Load method fails with:

enter image description here

Microsoft.JSInterop.JSException: 'Failed to fetch dynamically imported module: https://0.0.0.1/_content/MyCompany/MyLib.js TypeError: Failed to fetch dynamically imported module: https://0.0.0.1/_content/MyCompany/MyLib.js'

What is wrong? The location of MyLib.js is not https://0.0.0.1/_content/?

Read Entire Article