Start Debugging

Fix: Failed to fetch dynamically imported module when importing a JS module from a Razor class library in Blazor

A Blazor app returns 404 for _content/{PackageId}/x.js when the Razor class library is referenced as a plain DLL. Use a ProjectReference or PackageReference, match the PackageId, or serve the files yourself.

This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process

If IJSRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/MyCompany.MyLib/MyLib.js") fails with Failed to fetch dynamically imported module, the server is answering that URL with a 404. A Razor class library’s JavaScript files are not inside its DLL: they travel through the static web assets manifest, which the SDK only builds for a ProjectReference or a PackageReference. Reference the library as a project or a NuGet package (a local folder feed is enough), make sure the path segment after _content/ is the library’s PackageId, and if you can only ship a DLL, copy the library’s published wwwroot next to the app and serve it under /_content/{PackageId}/ yourself. Everything below was reproduced on macOS with .NET SDK 10.0.302 (ASP.NET Core 10.0.10), a Blazor Web App with Interactive Server rendering, and Chromium.

The error in context

The C# side surfaces it as a JSException. The browser console shows the real cause, a 404, one line earlier:

Failed to load resource: the server responded with a status of 404 (Not Found)

Microsoft.JSInterop.JSException: Failed to fetch dynamically imported module:
http://localhost:5071/_content/MyCompany.MyLib/MyLib.js
TypeError: Failed to fetch dynamically imported module:
http://localhost:5071/_content/MyCompany.MyLib/MyLib.js

In a .NET MAUI Blazor Hybrid app the origin is https://0.0.0.1/ instead of localhost, which is how the Stack Overflow question that prompted this post shows it.

Why the module 404s

import() in the browser is just an HTTP GET. The C# part of a Razor class library (RCL) loads fine from any reference, so components render and the error only appears when the JavaScript is fetched. The files behind /_content/{PACKAGE ID}/ come from somewhere else, and there are three common reasons they are missing:

  1. The RCL is referenced as a DLL (<Reference Include="..." HintPath="..." />, or a DLL dropped into a folder). No static web assets are registered at all. This is the most common cause and the one in the question.
  2. The path uses the assembly name, but the library has a different PackageId. The prefix is _content/{PackageId}/, and the PackageId only defaults to the assembly name.
  3. A collocated Component.razor.js is imported without its folder or without the leading ./. The URL must mirror the file’s location inside the RCL project.

Minimal repro

An RCL named MyCompany.MyLib, created with dotnet new razorclasslib -f net10.0, with one module in wwwroot and one collocated with a component:

// .NET 10 RCL: MyCompany.MyLib/wwwroot/MyLib.js
export function getOffset(el) {
  const r = el.getBoundingClientRect();
  return { x: Math.round(r.left), y: Math.round(r.top) };
}
// .NET 10 RCL: MyCompany.MyLib/Probe.razor.js (collocated with Probe.razor)
export function hello() { return "hello from Probe.razor.js"; }
@* .NET 10 RCL: MyCompany.MyLib/Probe.razor *@
@inject IJSRuntime JS
@implements IAsyncDisposable

<div @ref="box" style="margin-left:40px">probe</div>
<p>@libResult</p>
<p>@coloResult</p>

@code {
    private ElementReference box;
    private IJSObjectReference? lib, colo;
    private string libResult = "pending", coloResult = "pending";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender) return;
        try
        {
            lib = await JS.InvokeAsync<IJSObjectReference>(
                "import", "./_content/MyCompany.MyLib/MyLib.js");
            var p = await lib.InvokeAsync<Point>("getOffset", box);
            libResult = $"wwwroot module OK: x={p.X}";
        }
        catch (JSException ex) { libResult = "wwwroot module FAILED: " + ex.Message.Split('\n')[0]; }
        try
        {
            colo = await JS.InvokeAsync<IJSObjectReference>(
                "import", "./_content/MyCompany.MyLib/Probe.razor.js");
            coloResult = "collocated module OK: " + await colo.InvokeAsync<string>("hello");
        }
        catch (JSException ex) { coloResult = "collocated module FAILED: " + ex.Message.Split('\n')[0]; }
        StateHasChanged();
    }

    public async ValueTask DisposeAsync()
    {
        try
        {
            if (lib is not null) await lib.DisposeAsync();
            if (colo is not null) await colo.DisposeAsync();
        }
        catch (JSDisconnectedException) { }
    }

    private record Point(int X, int Y);
}

The host is dotnet new blazor -f net10.0 --interactivity Server, with Home.razor reduced to @rendermode InteractiveServer and <MyCompany.MyLib.Probe />. The only thing that changes between runs is how HostApp.csproj references the library. Results from curl -o /dev/null -w "%{http_code}" against the running app, and the text the component rendered in the browser:

How the host references the RCLMyLib.jsProbe.razor.jsRendered
<ProjectReference>200200both OK
<Reference HintPath="..\libs\MyCompany.MyLib.dll">404404both FAILED
<PackageReference> from a local folder feed200200both OK

With the DLL reference, the component itself rendered (the “probe” div was there), which is why this error is confusing: the library “works” until the first import.

The build output explains it. With a ProjectReference, bin/Debug/net10.0/HostApp.staticwebassets.runtime.json contains a _content node:

['background.png', 'exampleJsInterop.js', 'exampleJsInterop.js.gz', ..., 'MyLib.js', 'MyLib.js.gz', 'Probe.razor.js', 'Probe.razor.js.gz']

With the DLL reference, the root of the same manifest has no _content node at all, only the app’s own app.css, favicon.png, _framework, and lib. MapStaticAssets (and UseStaticFiles in Development) serve exactly what the manifest lists, so the request falls through to a 404. The library’s scoped CSS bundle disappears for the same reason: the generated HostApp.styles.css no longer @imports _content/MyCompany.MyLib/MyCompany.MyLib.bundle.scp.css.

Fix 1: reference the library as a project or a package

This is the supported path and the only one that brings along everything the RCL ships: wwwroot files, collocated .razor.js modules, the scoped CSS bundle, fingerprinting, and compressed variants.

If the source is in the same repository, use a ProjectReference:

<!-- .NET 10, HostApp.csproj -->
<ItemGroup>
  <ProjectReference Include="..\MyCompany.MyLib\MyCompany.MyLib.csproj" />
</ItemGroup>

If the library lives “outside the consuming project”, as in the question, do not hand over a DLL. Pack it and consume the .nupkg. A folder works as a feed, so there is no need to publish anywhere:

dotnet pack MyCompany.MyLib -c Release -o ./feed -p:Version=1.0.0
<!-- .NET 10, nuget.config next to the solution -->
<configuration>
  <packageSources>
    <add key="local" value="./feed" />
  </packageSources>
</configuration>
<!-- .NET 10, HostApp.csproj -->
<ItemGroup>
  <PackageReference Include="MyCompany.MyLib" Version="1.0.0" />
</ItemGroup>

The package is what carries the assets. Its contents show why a bare DLL cannot work:

build/Microsoft.AspNetCore.StaticWebAssets.props
build/MyCompany.MyLib.props
lib/net10.0/MyCompany.MyLib.dll
staticwebassets/MyLib.js
staticwebassets/Probe.razor.js
staticwebassets/MyCompany.MyLib.nevv2e474g.bundle.scp.css
...

Microsoft.AspNetCore.StaticWebAssets.props declares one StaticWebAsset item per file with <BasePath>_content/MyCompany.MyLib</BasePath>. NuGet imports build/MyCompany.MyLib.props, which pulls that file into the consuming project, and the host’s runtime manifest then lists ~/.nuget/packages/mycompany.mylib/1.0.0/staticwebassets/ as a content root. Each item also carries <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>, so publish copies the files under the app’s wwwroot/_content/MyCompany.MyLib/. In this repro both modules returned 200 after switching to the package, with no code change in the library.

If you change the library and re-pack with the same version, NuGet keeps serving the cached copy. Bump the version or clear ~/.nuget/packages/mycompany.mylib while iterating.

Fix 2: use the PackageId in the path, not the assembly name

The URL segment after _content/ is the library’s PackageId. Microsoft’s RCL static assets docs state that it defaults to the project’s assembly name only if <PackageId> is not set. Adding one line to the RCL:

<!-- .NET 10, MyCompany.MyLib.csproj -->
<PropertyGroup>
  <PackageId>MyCompany</PackageId>
</PropertyGroup>

changed the host’s runtime manifest from _content/MyCompany.MyLib/... to:

{'MyCompany': ['exampleJsInterop.js', 'MyLib.js', 'Probe.razor.js']}

So the library’s own hard-coded "./_content/MyCompany.MyLib/MyLib.js" now 404s, even with a perfectly good ProjectReference. The URL in the original question, _content/MyCompany/MyLib.js, has exactly this shape, so check the RCL’s PackageId (including one set in a Directory.Build.props) before anything else. Whichever value you choose, keep the import string in the library in sync with it, ideally in one constant:

// .NET 10, inside MyCompany.MyLib
internal static class Assets
{
    // Must match <PackageId> of this project (defaults to the assembly name).
    public const string Base = "./_content/MyCompany.MyLib/";
}

Fix 3: get the collocated module path right

For a collocated file, the path after the PackageId is the component’s folder inside the RCL plus {Component}.razor.js, and the leading ./ is required (see JavaScript location in Blazor apps). Probe.razor.js sits at the project root, so it is ./_content/MyCompany.MyLib/Probe.razor.js. If it were Components/Probe.razor.js, the URL would be ./_content/MyCompany.MyLib/Components/Probe.razor.js. A wrong folder gives the same “Failed to fetch dynamically imported module”, even though every other asset from the library loads.

Fix 4: when you really can only ship a DLL

Sometimes the library comes from a vendor as binaries, or a build system only allows a file reference. Then the host has to put the files at the URL the library expects. Start from the RCL’s publish output, which contains the DLL plus a wwwroot folder with every asset, including collocated modules and the CSS bundle:

dotnet publish MyCompany.MyLib -c Release -o ./libpub
# libpub/MyCompany.MyLib.dll
# libpub/wwwroot/MyLib.js
# libpub/wwwroot/Probe.razor.js
# libpub/wwwroot/MyCompany.MyLib.styles.css
# libpub/wwwroot/exampleJsInterop.js, background.png

Ship MyCompany.MyLib.dll and that wwwroot folder together (here in libs/MyCompany.MyLib/).

The obvious attempt fails with BLAZOR106

Linking the folder into the host’s wwwroot/_content/... as Content items, or simply copying it into wwwroot/_content/MyCompany.MyLib/, breaks the build as soon as a collocated module is involved:

error BLAZOR106: The JS module file '.../HostApp/wwwroot/_content/MyCompany.MyLib/Probe.razor.js'
was defined but no associated razor component or view was found for it.

The SDK’s ResolveJSModuleStaticWebAssets target treats every Content or None item matching **/*.razor.js as a collocated module of the host project and requires a matching .razor file in that project. If the library has no collocated modules (or you exclude them), linked Content items do work:

<!-- .NET 10, HostApp.csproj: works for wwwroot modules only -->
<ItemGroup>
  <Reference Include="MyCompany.MyLib">
    <HintPath>..\libs\MyCompany.MyLib\MyCompany.MyLib.dll</HintPath>
  </Reference>
  <Content Include="..\libs\MyCompany.MyLib\wwwroot\**"
           Exclude="..\libs\MyCompany.MyLib\wwwroot\**\*.razor.js"
           Link="wwwroot\_content\MyCompany.MyLib\%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>

With that, MyLib.js returned 200 and Probe.razor.js 404, as expected.

A version that also serves collocated modules

Keep the files out of the item groups the Razor SDK scans: copy them with a Copy task into the output and publish folders, then serve that folder under the _content prefix with a second static files middleware.

<!-- .NET 10, HostApp.csproj -->
<ItemGroup>
  <Reference Include="MyCompany.MyLib">
    <HintPath>..\libs\MyCompany.MyLib\MyCompany.MyLib.dll</HintPath>
  </Reference>
</ItemGroup>

<!-- A Copy task, not Content/None items, so the Razor SDK does not
     treat Probe.razor.js as a module of this project (BLAZOR106). -->
<ItemGroup>
  <MyLibAssets Include="..\libs\MyCompany.MyLib\wwwroot\**"
               Exclude="..\libs\MyCompany.MyLib\wwwroot\**\*.gz;..\libs\MyCompany.MyLib\wwwroot\**\*.br" />
</ItemGroup>
<Target Name="CopyMyLibAssetsOnBuild" AfterTargets="Build">
  <Copy SourceFiles="@(MyLibAssets)"
        DestinationFiles="@(MyLibAssets->'$(OutDir)mylib-assets\%(RecursiveDir)%(Filename)%(Extension)')"
        SkipUnchangedFiles="true" />
</Target>
<Target Name="CopyMyLibAssetsOnPublish" AfterTargets="Publish">
  <Copy SourceFiles="@(MyLibAssets)"
        DestinationFiles="@(MyLibAssets->'$(PublishDir)mylib-assets\%(RecursiveDir)%(Filename)%(Extension)')"
        SkipUnchangedFiles="true" />
</Target>
// .NET 10, HostApp/Program.cs (Blazor Web App template), before MapStaticAssets
using Microsoft.Extensions.FileProviders;

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(AppContext.BaseDirectory, "mylib-assets")),
    RequestPath = "/_content/MyCompany.MyLib"
});

app.MapStaticAssets();

AppContext.BaseDirectory is the bin folder under dotnet run and the publish folder in production, so the same code works in both. In this repro both modules returned 200 with Content-Type: text/javascript under dotnet run, the page rendered “wwwroot module OK” and “collocated module OK”, and a dotnet publish -c Release copy started from the publish folder served both files too.

What you give up compared to Fix 1: no fingerprinted URLs, no precompressed variants, no automatic CSS bundle import (add <link rel="stylesheet" href="_content/MyCompany.MyLib/MyCompany.MyLib.styles.css" /> to App.razor yourself), and you have to re-copy the folder every time the DLL changes. That is a lot of manual bookkeeping to avoid a .nupkg, which is why packing is the better answer whenever the library’s owner can produce one.

Gotchas and lookalikes

  • The path in the browser is relative to the base URL. ./_content/... resolves against the page’s <base href>. An app hosted under a sub-path needs the matching <base href="/myapp/" />, otherwise the module request goes to the wrong folder and 404s with the same message.
  • Blazor WebAssembly standalone and MAUI Blazor Hybrid were not reproduced here. The same manifest mechanism applies to both, so Fix 1 and Fix 2 hold. Fix 4’s UseStaticFiles part needs an ASP.NET Core server, so it does not apply to a standalone WebAssembly app or to a BlazorWebView. For those, ship a package.
  • A module that 404s only after deployment, for a package you never referenced, is usually the Debug-only hot reload module. That case is covered in the HotReload lib.module.js failed-to-fetch fix.
  • JavaScript interop calls cannot be issued at this time is a different failure: the import call ran during prerendering, before there is a browser to run it. Keep imports in OnAfterRenderAsync, as above, and see the prerendering JS interop fix.
  • Two asset sources mapped to the same URL are a build error, not a runtime 404. If you see Conflicting assets with the same target path after experimenting with copies of the library’s files, see the conflicting assets fix.

Sources

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.