Bundles

From Logic Wiki
Jump to: navigation, search
MVC Bundles.png
install WebGrease nuget package first

/View/Shared/_Layout.cshtml

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/bootstrap.min.js")
@RenderSection("scripts", required: false)
@RenderSection("inlineScripts", false)

/App_Start/BundleConfig.cs

public class BundleConfig
  public static void RegisterBundles(BundleCollection bundles)
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));	
    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*"));

/View/AnyPage.cshtml

@section Scripts {
   @Scripts.Render("~/bundles/jqueryval")
}

@section inlineScripts {
   <script type="text/javascript">
       $(function () {
           $('select').change(function () {
               var txt = $(this).val();
              ………………………
          });
   </script>
}

/View/Shared/_Layout.cshtml

@Styles.Render("~/Content/bootstrap.min.css")
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")

/App_Start/BundleConfig.cs

public class BundleConfig
  public static void RegisterBundles(BundleCollection bundles)
    bundles.Add(new StyleBundle("~/Content/themes/base/css").Include("~/Content/themes/base/jquery.ui.core.css", "~/Content/themes/base/jquery.ui.resizable.css",

Global.asax.cs

       protected void Application_Start()
       {
           BundleConfig.RegisterBundles(BundleTable.Bundles);
       }

The 'Gotcha'

There is a 'Gotcha' to be avoided here that seems to be missed from almost every piece of documentation I have seen. It is the fact that the bundle path e.g. "~/bundles/css" in the code @Styles.Render("~/bundles/css"), should not exist on the file system. It is a 'virtual' path that is used as a name not as a path to any physical files. If this path exists on the file system, the bundle will not be loaded.

Image Urls

If you define your bundle as:

bundles.Add(new StyleBundle("~/Content/FrontEnd/css/bundle")
      .Include("~/Content/FrontEnd/css/*.css"));

Where you define the bundle on the same path as the source files that made up the bundle, the relative image paths will still work. The last part of the bundle path is really the file name for that specific bundle (i.e., /bundle can be any name you like).

This will only work if you are bundling together CSS from the same folder (which I think makes sense from a bundling perspective).

Or

Alternatively this may now be achieved by applying a CssRewriteUrlTransformation (Change relative URL references to CSS files when bundled).

bundles.Add(new StyleBundle("~/Content/css/jquery-ui/bundle")
      .Include("~/Content/css/jquery-ui/*.css", new CssRewriteUrlTransform()));