ASP.NET MVC4 Bundle a single file

前端 未结 3 1299
南方客
南方客 2021-02-14 18:57

Is there a way to bundle a single file using the new bundling features in MVC4? I know bundling a single file doesn\'t make much sense but I\'d like to use server-side minificat

3条回答
  •  [愿得一人]
    2021-02-14 19:35

    I needed something like this, and here's what I came up with

    On a view I can add a script or style with an HTML Helper. These will each accept n number of parameters.

    @Html.Style("~/Styles/someFile.css")
    @Html.Script("~/Scripts/foo.js", "~/Scripts/bar.js")
    

    So I created an extention to handle this for me. Here's what the class looks like.

    using System.Linq;
    using System.Web.Optimization;
    
    namespace System.Web.Mvc
    {
        public static class HtmlHelperExtensions
        {
    
            public static IHtmlString Script(this HtmlHelper helper, params string[] urls)
        {
            var bundleDirectory = "~/Scripts/bundles/" + MakeBundleName(".js", urls);
            var thisBundle = new ScriptBundle(bundleDirectory).Include(urls);
            BundleTable.Bundles.Add(thisBundle);
    
            return Scripts.Render(bundleDirectory);
        }
    
        public static IHtmlString Style(this HtmlHelper helper, params string[] urls)
        {
            var bundleDirectory = "~/Styles/bundles/" + MakeBundleName(".css", urls);
            var thisBundle = new StyleBundle(bundleDirectory).Include(urls);
            BundleTable.Bundles.Add(thisBundle);
    
            return Styles.Render(bundleDirectory);
        }
    
        private static string MakeBundleName(string type, params string[] urls)
        {
            var bundleSections = new List();
    
            foreach (var item in urls)
            {
                bundleSections.Add(item.Replace("~/", "").Replace("/", ".").Replace(type, ""));
            }
    
            return string.Join("+", bundleSections.ToArray());
        }
        }
    }
    

    Caveats

    This does hard code where the bundle "virtual directory" exists. So if you have any relative paths to images or anything else in your files, they will break. For our use case, this works fine for us for now.

    The bundle names are auto-generated. Again, this works for us, but it could be better. I could see a simple improvement to this where you must provide a bundle path & name that would have a syntax like this: @Html.Script("~/bundles/myBundleName","~/Scripts/foo.js", "~/Scripts/bar.js")


    I'd be happy to hear about any improvements anyone might have for this.

提交回复
热议问题