Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ASP.NET MVC bundle manager to render a script tag with the type = "module" attribute?

When we add a bundle to the ASP.NET MVC bundle collection like so:

public static RegisterBundles(BundleCollection bundles)
{

  bundles.Add( new ScriptBundle("~/bundle/foo")
               .Include("~/Scripts/foo.js"));
}

And render it in a view like so:

@Scripts.Render("~/bundle/foo")

It gets rendered like a regular javascript file inclusion <script> like so:

<script src = "/Scripts/foo.js"></script>

But my foo.js is an ES 6 module and so I'd like it to load like so:

<script src = "/Scripts/foo.js" type = "module"></script>

Short of typing that <script> tag myself, how do I actually get the ASP.NET MVC bundle classes to render it this way?

I am using ASP.NET MVC 5.2.4 targeting the .NET framework version 4.6.1.

like image 720
Water Cooler v2 Avatar asked Feb 04 '23 19:02

Water Cooler v2


1 Answers

I assumed that you have latest Microsoft.AspNet.Web.Optimization package installed, hence you could use Scripts.RenderFormat() to add type attribute on generated <script> tag:

@Scripts.RenderFormat("<script src='{0}' type='module'></script>", "~/bundle/foo")

Or you could utilize a helper class containing helper method to render <script> tags with additional attribute for certain bundles:

public static class ScriptHelpers
{
    public static IHtmlString RenderWithTypeAttribute(params string[] paths)
    {
        return System.Web.Optimization.Scripts.RenderFormat(@"<script src=""{0}"" type=""module""></script>", paths);
    }
}

And then use it in Razor view page like this:

@ScriptHelpers.RenderWithTypeAttribute("~/bundle/foo")

Reference:

How to render Scripts/Styles bundles in the custom format in ASP.NET MVC?

Related issue:

Set Script Type in MVC4 Script Bundle

like image 195
Tetsuya Yamamoto Avatar answered Feb 06 '23 09:02

Tetsuya Yamamoto