5.8. Bundles

Bundles are used to make it easier to link JavaScript scripts and CSS files. You can link CSS bundles with the Styles.Render helper and script bundles with the Scripts.Render helper.

Bundles are registered in the BundleConfig.cs file located in the App_Start folder:

  1. public static void RegisterBundles(BundleCollection bundles)
  2. {
  3. bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
  4. "~/Scripts/jquery-{version}.js"));
  5. bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
  6. "~/Scripts/jquery.validate*"));
  7. bundles.Add(new ScriptBundle("~/bundles/jquery-ui").Include(
  8. "~/Scripts/jquery-ui-{version}.js"));
  9. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
  10. "~/Scripts/modernizr-*"));
  11. bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
  12. "~/Scripts/bootstrap.js",
  13. "~/Scripts/respond.js"));
  14. bundles.Add(new StyleBundle("~/Content/css").Include(
  15. "~/Content/jquery-ui.min.css",
  16. "~/Content/themes/ui-darkness/jquery-ui.min.css",
  17. "~/Content/themes/ui-darkness/theme.css",
  18. "~/Content/bootstrap.min.css",
  19. "~/Content/Site.css"
  20. ));
  21. }

The RegisterBundles method adds all created bundles to the bundles collection. A bundle is declared in the following way:

  1. new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js")

The virtual path of the bundle is passed to the ScriptBundle construct. Specific script files are included in this bundle using the Include method.

The {version} parameter in the “~/Scripts/jquery-{version}.js” expression is a placeholder for any string referring to the script version. It is very handy because it allows the version of the library to be changed later without having to change anything in the code. The system will accept the new version automatically.

The “~/Scripts/jquery.validate*” expression fills out the rest of the string with the asterisk character as a wildcard. For example, the expression will include two files at once in the bundle: jquery.validate.js and jquery.validate.unobtrusive.js, along with their minimized versions, because their names both start with “jquery.validate”.

The same applies when creating CSS bundles, using the StyleBundle class.

The full versions of the scripts and cascading style sheets should be used in the debug mode and the minimized ones in the release mode. Bundles allow you to solve this problem. When you run the application in the debug mode, the web.config files have the <compilation debug=”true”> parameter. When you set this parameter to false (the Release mode), the minimized version of JavaScript modules and CSS files will be used instead of the full ones.