[英]How to get the ASP.NET MVC bundle manager to render a script tag with the type = “module” attribute?
當我們像這樣將捆綁包添加到ASP.NET MVC捆綁包集合中時:
public static RegisterBundles(BundleCollection bundles)
{
bundles.Add( new ScriptBundle("~/bundle/foo")
.Include("~/Scripts/foo.js"));
}
並在這樣的視圖中渲染它:
@Scripts.Render("~/bundle/foo")
它像常規的JavaScript文件包含<script>
一樣呈現:
<script src = "/Scripts/foo.js"></script>
但是我的foo.js是ES 6模塊,因此我希望這樣加載:
<script src = "/Scripts/foo.js" type = "module"></script>
除了自己鍵入<script>
標簽之外,我實際上如何獲得ASP.NET MVC捆綁軟件類以這種方式呈現它?
我正在使用針對.NET Framework 4.6.1版本的ASP.NET MVC 5.2.4。
我假設您已經安裝了最新的Microsoft.AspNet.Web.Optimization
包,因此可以使用Scripts.RenderFormat()
在生成的<script>
標記上添加type
屬性:
@Scripts.RenderFormat("<script src='{0}' type='module'></script>", "~/bundle/foo")
或者,您可以利用包含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);
}
}
然后在Razor視圖頁面中使用它,如下所示:
@ScriptHelpers.RenderWithTypeAttribute("~/bundle/foo")
參考:
如何在ASP.NET MVC中以自定義格式呈現腳本/樣式包?
相關問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.