ASP.NET Core MVC Tag helpers for working with JavaScript modules and import maps.
Install the AspNetCoreJsModules NuGet package:
Install-Package AspNetCoreJsModules
Or via the .NET Core command line interface:
dotnet add package AspNetCoreJsModules
Add services to your application's Startup
class:
using AspNetCoreJsModules;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddJsModules();
}
}
In your _ViewImports.cshtml
file:
@addTagHelper *, AspNetCoreJsModules
The <js-modules>
tag helper generates an import map was as script type="module"
and link rel="modulepreload"
elements for every <js-import>
on the page. Each <js-import>
requires a name
and path
attribute. The path
attribute can reference a local or remote file. For local files, you can set append-version="true"
to have ASP.NET Core append a version hash.
<js-modules>
<js-import name="@@hotwired/stimulus" path="https://unpkg.com/@@hotwired/[email protected]/dist/stimulus.js" />
<js-import name="MyModule" path="~/modules/my-module.js" append-version="true" />
</js-modules>
Renders:
<script type="importmap">
{
"imports": {
"@hotwired/stimulus": "https://unpkg.com/@hotwired/[email protected]/dist/stimulus.js",
"MyModule": "/modules/my-module.js?v=NDJARtKDTcKIE8ytjKwNo_-SSH8LKz_chEuHcASozBk"
}
}
</script>
<script src="https://unpkg.com/@hotwired/[email protected]/dist/stimulus.js" type="module"></script>
<script src="/modules/my-module.js?v=NDJARtKDTcKIE8ytjKwNo_-SSH8LKz_chEuHcASozBk" type="module"></script>
<link href="https://unpkg.com/@hotwired/[email protected]/dist/stimulus.js" rel="modulepreload" />
<link href="/modules/my-module.js?v=NDJARtKDTcKIE8ytjKwNo_-SSH8LKz_chEuHcASozBk" rel="modulepreload" />
You can also add modules from code:
using AspNetCoreJsModules;
JsModuleContext jsModuleContext = HttpContext.GetJsModuleContext();
jsModuleContext.AddModuleImport("my-module", "path-to-my-module.js");