将不同的 Bundle Virtual Path 联合成一个

Joint different Bundles Virtual Path into single one

我在 BundleConfig.config 上定义了多个 Bundle 虚拟路径,其中每个虚拟路径都关联了多个 javascript 路径文件。

我想要的是将所有这些虚拟路径合并为一个。

例如,我有以下代码:

bundles.Add(new ScriptBundle(BundlesVirtualPaths.EditorV2.Main).Include(
                                "~/Scripts/EditorV2/main.js"
                    ));

bundles.Add(new ScriptBundle(BundlesVirtualPaths.EditorV2.Main2).Include(
                                "~/Scripts/EditorV2/main2.js"
                    ));

bundles.Add(new ScriptBundle(BundlesVirtualPaths.EditorV2.Main3).Include(
                                "~/Scripts/EditorV2/main3.js"
                    ));

我想要的是做这样的事情:

bundles.Add(new ScriptBundle(BundlesVirtualPaths.EditorV2.AllScripts).Include(
                            BundlesVirtualPaths.EditorV2.Main,
                            BundlesVirtualPaths.EditorV2.Main2,
                            BundlesVirtualPaths.EditorV2.Main3
                ));

这可以做到吗?我可以吗?

您可以尝试这样的操作:

public static class BundleHelpers
{
    public static BundleCollection JoinScriptBundle(this BundleCollection bundleCollection, string virtualPath, params string[] bundlesToJoin)
    {
        var bundleResolver = new BundleResolver(bundleCollection);
        Bundle allScriptBundle = new ScriptBundle(virtualPath);
        foreach (var bundle in bundlesToJoin)
        {
            foreach (var scriptPath in bundleResolver.GetBundleContents(bundle))
            {
                allScriptBundle = allScriptBundle.Include(scriptPath);
            }
        }
        bundleCollection.Add(allScriptBundle);
        return bundleCollection;
    }
}

然后您可以加入您的捆绑包:

bundles.JoinScriptBundle("~/bundle/allscript", "~/bundles/jquery", "~/bundles/jqueryval", "~/bundles/modernizr");

是的,您可以这样做,因为您正试图将所有 JS 文件合并为一个 bundle,这是正确的方法,但可能不会每次都出现相同的情况。所以你需要做基于类型的捆绑如下

对于目录:

 bundles.Add(new Bundle("~/js/vendor").IncludeDirectory(@"~/Scripts/vendors/JQuery", "*.js")
                                                     .IncludeDirectory(@"~/Scripts/vendors/Knockout", "*.js")
                                                     .IncludeDirectory(@"~/Scripts/vendors", "*.js"));

对于文件:

 bundles.Add(new Bundle("~/js/kendo").Include("~/Scripts/kendo/kendo.core.min.js")
                                        .Include("~/Scripts/kendo/kendo.data.min.js")
                                        .Include("~/Scripts/kendo/kendo.binder.min.js")
                                        .Include("~/Scripts/kendo/kendo.calendar.min.js")

对于url:

var CdnPath = "http://fonts.googleapis.com/css?family=Open+Sans:300";
bundles.Add(new ScriptBundle("mybarbundle", CdnPath).Include("~/Scripts/jquery-{version}.js"));