【问题标题】:Web.Optimizations - any way to get all includes from a Style/Script Bundle?Web.Optimizations - 从样式/脚本包中获取所有内容的任何方式?
【发布时间】:2013-01-31 01:10:51
【问题描述】:

我正在处理一些基于配置添加 CSS 和 JS 文件的动态捆绑。

我启动了一个新的 StyleBundle,这样:

var cssBundle = new StyleBundle("~/bundle/css");

然后遍历配置并添加任何找到的包含:

cssBundle.Include(config.Source);

在循环之后,我想检查是否实际上包含任何文件/目录。我知道有 EnumerateFiles() 但我认为这 100% 不能达到目的。

其他人以前做过类似的事情吗?

【问题讨论】:

    标签: c# asp.net asp.net-mvc bundling-and-minification asp.net-optimization


    【解决方案1】:

    Bundle 类使用了一个内部项目列表,该列表不暴露给应用程序,并且不一定可以通过反射访问(我尝试过但无法获取任何内容)。您可以使用 BundleResolver 类获取一些相关信息,如下所示:

    var cssBundle = new StyleBundle("~/bundle/css");
    cssBundle.Include(config.Source);
    
    // if your bundle is already in BundleTable.Bundles list, use that.  Otherwise...
    var collection = new BundleCollection();
    collection.Add(cssBundle)
    
    // get bundle contents
    var resolver = new BundleResolver(collection);
    List<string> cont = resolver.GetBundleContents("~/bundle/css").ToList();
    

    如果您只需要计数,那么:

    int count = resolver.GetBundleContents("~/bundle/css").Count();
    

    编辑:使用反射

    显然我之前的反射测试做错了。

    这确实有效:

    using System.Reflection;
    using System.Web.Optimization;
    
    ...
    
    int count = ((ItemRegistry)typeof(Bundle).GetProperty("Items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(cssBundle, null)).Count;
    

    您当然应该在那里添加一些安全检查,并且像许多反射示例一样,这违反了 Items 属性的预期安全性,但它确实有效。

    【讨论】:

    • 感谢 Corey 看起来不错,我唯一的问题是捆绑包被添加到集合中以便计算其内容。理想情况下,我想检查内容以确保在添加到集合之前 > 0。这有意义吗?
    • 您可以使用反射示例来获取计数,或者像我在上面的初始代码示例中那样创建一个新的(和临时的)集合,并使用BundleResolver 来获取包含文件的列表.除非您将捆绑包添加到 BundleTable.Bundles 集合中,否则该捆绑包不会对系统的其余部分可用,因此您可以使用任一方法检查捆绑包,然后再使其普遍可用。
    • ItemRegistry 不是内部的吗?
    • @Corey,GetBundleContents() 不会返回丢失的文件,所以回到 TS 的问题“我想检查是否实际上包含任何文件/目录”,这似乎没有成为一个解决方案。
    • @HermanKan 反射方法应该为您提供已创建的列表,但您必须从那里执行一些文件枚举代码才能获取实际的文件列表。
    【解决方案2】:

    Bundle可以使用以下扩展方法:

    public static class BundleHelper
    {
        private static Dictionary<Bundle, List<string>> bundleIncludes = new Dictionary<Bundle, List<string>>();
        private static Dictionary<Bundle, List<string>> bundleFiles = new Dictionary<Bundle, List<string>>();
    
        private static void EnumerateFiles(Bundle bundle, string virtualPath)
        {
            if (bundleIncludes.ContainsKey(bundle))
                bundleIncludes[bundle].Add(virtualPath);
            else
                bundleIncludes.Add(bundle, new List<string> { virtualPath });
    
            int i = virtualPath.LastIndexOf('/');
            string path = HostingEnvironment.MapPath(virtualPath.Substring(0, i));
    
            if (Directory.Exists(path))
            {
                string fileName = virtualPath.Substring(i + 1);
                IEnumerable<string> fileList;
    
                if (fileName.Contains("{version}"))
                {
                    var re = new Regex(fileName.Replace(".", @"\.").Replace("{version}", @"(\d+(?:\.\d+){1,3})"));
                    fileName = fileName.Replace("{version}", "*");
                    fileList = Directory.EnumerateFiles(path, fileName).Where(file => re.IsMatch(file));
                }
                else // fileName may contain '*'
                    fileList = Directory.EnumerateFiles(path, fileName);
    
                if (bundleFiles.ContainsKey(bundle))
                    bundleFiles[bundle].AddRange(fileList);
                else
                    bundleFiles.Add(bundle, fileList.ToList());
            }
        }
    
        public static Bundle Add(this Bundle bundle, params string[] virtualPaths)
        {
            foreach (string virtualPath in virtualPaths)
                EnumerateFiles(bundle, virtualPath);
    
            return bundle.Include(virtualPaths);
        }
    
        public static Bundle Add(this Bundle bundle, string virtualPath, params IItemTransform[] transforms)
        {
            EnumerateFiles(bundle, virtualPath);
            return bundle.Include(virtualPath, transforms);
        }
    
        public static IEnumerable<string> EnumerateIncludes(this Bundle bundle)
        {
            return bundleIncludes[bundle];
        }
    
        public static IEnumerable<string> EnumerateFiles(this Bundle bundle)
        {
            return bundleFiles[bundle];
        }
    }
    

    然后只需将您的 Include() 调用替换为 Add():

    var bundle = new ScriptBundle("~/test")
        .Add("~/Scripts/jquery/jquery-{version}.js")
        .Add("~/Scripts/lib*")
        .Add("~/Scripts/model.js")
        );
    
    var includes = bundle.EnumerateIncludes();
    var files = bundle.EnumerateFiles();
    

    如果您也在使用IncludeDirectory(),只需添加相应的AddDirectory() 扩展方法即可完成示例。

    【讨论】:

    • 一个 'EnumerateFiles' 方法实际上内置在 Bundle 类中。它将返回一个 BundleFile 对象列表,您不仅可以访问每个文件的路径,还可以访问每个文件的 IItemTransform(s),如果有的话。
    猜你喜欢
    • 2013-12-03
    • 2020-05-26
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 2022-01-05
    • 2012-09-22
    • 1970-01-01
    • 2014-01-15
    相关资源
    最近更新 更多