[英]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: 当我们像这样将捆绑包添加到ASP.NET MVC捆绑包集合中时:
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: 它像常规的JavaScript文件包含
<script>
一样呈现:
<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: 但是我的foo.js是ES 6模块,因此我希望这样加载:
<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? 除了自己键入
<script>
标签之外,我实际上如何获得ASP.NET MVC捆绑软件类以这种方式呈现它?
I am using ASP.NET MVC 5.2.4 targeting the .NET framework version 4.6.1. 我正在使用针对.NET Framework 4.6.1版本的ASP.NET MVC 5.2.4。
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: 我假设您已经安装了最新的
Microsoft.AspNet.Web.Optimization
包,因此可以使用Scripts.RenderFormat()
在生成的<script>
标记上添加type
属性:
@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: 或者,您可以利用包含helper方法的helper类来渲染具有某些捆绑包附加属性的
<script>
标签:
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: 然后在Razor视图页面中使用它,如下所示:
@ScriptHelpers.RenderWithTypeAttribute("~/bundle/foo")
Reference: 参考:
How to render Scripts/Styles bundles in the custom format in ASP.NET MVC? 如何在ASP.NET MVC中以自定义格式呈现脚本/样式包?
Related issue: 相关问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.