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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With