Skip to content

Latest commit

 

History

History
80 lines (57 loc) · 2.46 KB

README.md

File metadata and controls

80 lines (57 loc) · 2.46 KB

AspNetCoreJsModules

ASP.NET Core MVC Tag helpers for working with JavaScript modules and import maps.

ci Nuget (with prereleases)

Installation

1. Install NuGet package

Install the AspNetCoreJsModules NuGet package:

Install-Package AspNetCoreJsModules

Or via the .NET Core command line interface:

dotnet add package AspNetCoreJsModules

2. Configure your ASP.NET Core application

Add services to your application's Startup class:

using AspNetCoreJsModules;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddJsModules();
    }
}

3. Register tag helpers

In your _ViewImports.cshtml file:

@addTagHelper *, AspNetCoreJsModules

Working with modules and import maps

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" />

Adding modules from outside tag helpers

You can also add modules from code:

using AspNetCoreJsModules;

JsModuleContext jsModuleContext = HttpContext.GetJsModuleContext();
jsModuleContext.AddModuleImport("my-module", "path-to-my-module.js");