asp.net mvc exclude css file from bundle

前端 未结 4 1317
庸人自扰
庸人自扰 2020-12-06 09:46

I have such bundle

bundles.Add(new StyleBundle(\"~/Content/themes/default/css\")
       .IncludeDirectory(\"~/Content/themes/Default\", \"*.css\"));
<         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 09:58

    I have improved the good suggestion by Jon Malcolm (and some updates by Satpal here) to fix few shortcomings that it had:

    1) It breaks the default behavior of the bundles with ".min." files

    2) It does not allow search patterns, but only files to be excluded

    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Optimization;
    
    
    public static class BundleExtentions
    {
        public static Bundle IncludeDirectoryWithExclusion(this Bundle bundle, string directoryVirtualPath, string searchPattern, bool includeSubDirectories, params string[] excludePatterns)
        {
            string folderPath = HttpContext.Current.Server.MapPath(directoryVirtualPath);
    
            SearchOption searchOption = includeSubDirectories
                                            ? SearchOption.AllDirectories
                                            : SearchOption.TopDirectoryOnly;
    
            HashSet excludedFiles = GetFilesToExclude(folderPath, searchOption, excludePatterns);
            IEnumerable resultFiles = Directory.GetFiles(folderPath, searchPattern, searchOption)
                                                        .Where(file => !excludedFiles.Contains(file) && !file.Contains(".min."));
    
            foreach (string resultFile in resultFiles)
            {
                bundle.Include(directoryVirtualPath + resultFile.Replace(folderPath, "")
                        .Replace("\\", "/"));
            }
    
            return bundle;
        }
    
        private static HashSet GetFilesToExclude(string path, SearchOption searchOptions, params string[] excludePatterns)
        {
            var result = new HashSet();
    
            foreach (string pattern in excludePatterns)
            {
                result.UnionWith(Directory.GetFiles(path, pattern, searchOptions));
            }
    
            return result;
        }
    }
    

    An example usage that I have is to include all the libraries from the lib folder starting with angular, but excluding all the locale scripts (because only one will be added based on the language in a separate bundle later):

    bundles.Add(new Bundle("~/bundles/scripts")
                    .Include("~/wwwroot/lib/angular/angular.js") // Has to be first
                    .IncludeDirectoryWithExclusion("~/wwwroot/lib", "*.js", true, "*.locale.*.js"));
    

    This will behave properly if you have both angular.min.js and angular.js and add unminified version in debug and using the existing .min.js in the release.

提交回复
热议问题