该问题的答案较晚,但 ASP.NET MVC 按字母顺序对文件进行排序。您还可以使用IBundleOrderer接口手动订购脚本文件。
例如,使用这样的自定义 IBundleOrderer 实现:
Bundle myBundle = new Bundle("~/bundles/SiteScripts", new JsMinify());
myBundle.IncludeDirectory("~/Scripts/SiteScripts", "*.js");
myBundle.Orderer = new MyBundleOrderer();
bundles.Add(myBundle);
MyBundleOrderer 从 web.config 文件中获取高优先级脚本:
public class MyBundleOrderer : IBundleOrderer
{
public IEnumerable<System.IO.FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files)
{
if (ConfigurationManager.AppSettings["HighPriorityScripts"] != null)
{
string[] highPriorityScripts = ConfigurationManager.AppSettings["HighPriorityScripts"].Split(',');
List<FileInfo> listFiles = new List<FileInfo>(files);
List<FileInfo> orderedFiles = new List<FileInfo>();
// Add high priority files in order :
foreach (string highPriorityFile in highPriorityScripts)
{
FileInfo nextFileInfo = listFiles.Find(delegate(FileInfo arg)
{
return arg.Name == highPriorityFile;
}
);
if (nextFileInfo != null)
{
orderedFiles.Add(nextFileInfo);
}
}
// Add remaining files to bundle :
foreach (FileInfo lowPriorityFile in listFiles)
{
if (!orderedFiles.Contains(lowPriorityFile))
{
orderedFiles.Add(lowPriorityFile);
}
}
return orderedFiles;
}
return files;
}
}