From 33cdc2f628c6c625a82eeda9d7f8df1b79a13fc1 Mon Sep 17 00:00:00 2001 From: Javier Calvarro Nelson Date: Mon, 5 Aug 2024 13:54:15 +0200 Subject: [PATCH] Preserve type attribute when defined in Script tag helper --- src/Mvc/Mvc.TagHelpers/src/ScriptTagHelper.cs | 5 +++ .../test/ScriptTagHelperTest.cs | 38 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/Mvc/Mvc.TagHelpers/src/ScriptTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/ScriptTagHelper.cs index 88da4462a9ad..64cc1be2f694 100644 --- a/src/Mvc/Mvc.TagHelpers/src/ScriptTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/ScriptTagHelper.cs @@ -265,6 +265,11 @@ public override void Process(TagHelperContext context, TagHelperOutput output) output.CopyHtmlAttribute(SrcAttributeName, context); } + if (Type != null) + { + output.CopyHtmlAttribute(TypeAttributeName, context); + } + // If there's no "src" attribute in output.Attributes this will noop. ProcessUrlAttribute(SrcAttributeName, output); diff --git a/src/Mvc/Mvc.TagHelpers/test/ScriptTagHelperTest.cs b/src/Mvc/Mvc.TagHelpers/test/ScriptTagHelperTest.cs index e6877cf7e8b3..e982e324a200 100644 --- a/src/Mvc/Mvc.TagHelpers/test/ScriptTagHelperTest.cs +++ b/src/Mvc/Mvc.TagHelpers/test/ScriptTagHelperTest.cs @@ -1025,6 +1025,44 @@ public void RenderScriptTags_GlobbedSrc_WithFileVersion_WithStaticAssets() Assert.Equal(expectedContent, content); } + [Theory] + [InlineData("~/js/site.js")] + [InlineData("/approot/js/site.js")] + public void RenderScriptTags_PathBase_WithFileVersion_UsingResourceCollection_PreservesModule(string path) + { + // Arrange + var context = MakeTagHelperContext( + attributes: new TagHelperAttributeList + { + new TagHelperAttribute("src", path), + new TagHelperAttribute("type", "module"), + new TagHelperAttribute("asp-append-version", "true") + }); + var output = MakeTagHelperOutput("script", attributes: new TagHelperAttributeList()); + + var urlHelperFactory = MakeUrlHelperFactory(value => + { + return value.StartsWith("~/", StringComparison.Ordinal) ? + value.Replace("~/", "/approot/") : + value; + }); + + var helper = GetHelper(urlHelperFactory: urlHelperFactory); + helper.ViewContext.HttpContext.SetEndpoint(CreateEndpoint()); + helper.ViewContext.HttpContext.Request.PathBase = "/approot"; + helper.Src = path; + helper.Type = "module"; + helper.AppendVersion = true; + + // Act + helper.Process(context, output); + + // Assert + Assert.Equal("script", output.TagName); + Assert.Equal("module", output.Attributes["type"].Value); + Assert.Equal("/approot/js/site.fingerprint.js", output.Attributes["src"].Value); + } + private static ScriptTagHelper GetHelper( IWebHostEnvironment hostingEnvironment = null, IUrlHelperFactory urlHelperFactory = null,