I’m working on a Blazor WebAssembly application and running into a problem when trying to import JavaScript modules. The browser keeps throwing an error saying it expected a JavaScript module but got HTML content instead. The error mentions strict MIME type checking for module scripts.
Here’s the code I’m using:
mapReference = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/MapHandler.js");
// Initialize the map component
await mapReference.InvokeVoidAsync("createMap", "mapContainer", componentRef, "errorContainer", apiKey);
This happens when I try to load external JavaScript files. Has anyone dealt with this before? What could be causing the server to return HTML instead of the JavaScript file?
This usually means your JavaScript file path is wrong or there’s a routing problem in your Blazor WASM setup. First, make sure MapHandler.js is actually at wwwroot/scripts/MapHandler.js and gets included when you publish. I’ve seen this tons of times - the file works fine during development but doesn’t make it into the build output. Also check your fallback routing in Blazor WASM. If it’s too aggressive, it’ll intercept JS file requests and serve index.html instead. Quick test: try hitting the JavaScript file directly in your browser with the full URL. See if it loads properly with the right content-type header.
I faced a similar issue with my Blazor WebAssembly app. The problem often arises when the server is not configured to serve static files correctly. When the browser requests a JavaScript file that isn’t found, it sometimes serves the index.html file instead, leading to a MIME type mismatch. Ensure that your JavaScript file is present in the wwwroot directory under the correct path. It might also be worth checking the server settings to confirm that static file serving is enabled, particularly if you’re using a reverse proxy or custom web server configuration.