Timvr01 Timvr01 - 2 months ago 8
Javascript Question

Bundling in asp.net

I'm using bundling in an ASP.net MVC application. I want to build my bundles in a hierarchical fashion.

For instance, these are the scripts I want on all my webpages:

bundles.Add(new ScriptBundle("~/bundles/bootstrap-js").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js",
"~/Scripts/bootstrap-datetimepicker.min.js",
"~/Scripts/jquery.smartmenus.js",
"~/Scripts/jquery.smartmenus.bootstrap.js"
));


Next I want to have for example knockout on only some pages:

bundles.Add(new ScriptBundle("~/bundles/knockout-js").Include(
"~/Scripts/knockout/knockout-3.4.0.js",
"~/Scripts/knockout/knockout-kendo.js",
"~/Scripts/knockout/knockout.mapping-latest.js",
"~/Scripts/knockout/knockout.validation.js",
"~/Scripts/knockout/knockout.validation.de-DE.js",
"~/Scripts/knockout/knockout.validation.fr-BE.js",
"~/Scripts/knockout/knockout.validation.nl-BE.js",
"~/Scripts/knockout/Knockout.bindinghandlers.js",
"~/Scripts/knockout/knockout.validation.mvc.js"));


And finally, I want every page to have it's own custom script.

bundles.Add(new ScriptBundle("~/bundles/scriptName-js").Include(
"~/Views/Cards/scriptName.js"));


Is there a way so I only have to include one @scripts.render statement by combining all previous bundles in to one bundle?

@Scripts.Render("~/bundles/mypage-js")


I tried this but it didn't work:

bundles.Add(new ScriptBundle("~/bundles/mypage-js").Include("~/bundles/scrip‌​tName-js","~/bundles‌​/knockout-js","~/bun‌​dles/bootstrap-js"))‌​;

Answer

There is an overload of Include that accepts an array of paths instead of a params of paths. You can use this to define blocks of shared scripts as string[] and then include them:

var everyPage =  new [] {
    "~/Scripts/bootstrap.js",
    "~/Scripts/respond.js",
    "~/Scripts/bootstrap-datetimepicker.min.js",
    "~/Scripts/jquery.smartmenus.js",
    "~/Scripts/jquery.smartmenus.bootstrap.js"
};

var knockout = new [] {
    "~/Scripts/knockout/knockout-3.4.0.js",
    "~/Scripts/knockout/knockout-kendo.js",
    //etc...
};

bundles.Add(new ScriptBundle("~/bundles/scriptName-js")
  .Include(everyPage)
  .Include(knockout)
  .Include("~/Views/Cards/scriptName.js")
);

It's not quite as succinct as referencing one bundle from another but it's better than repeating every block of scripts

Comments