Pages

Friday, May 9, 2014

MVC 4.5 Adding Bundling to Empty Project

Steps needed to add bundling to a new MVC 4.51 empty project.
Add reference: Microsoft.AspNet.Web.Optimization
from the Package Manager Console enter:
  • PM> Install-Package Microsoft.AspNet.Web.Optimization
image
Adding Microsoft.AspNet.Web.Optimization, added a reference to the System.Web.Optimization namespace.
System.Web.Optimization exposes:
  • BundleCollection: Contains and manages the set of registered Bundle objects in an ASP.NET application.
  • ScriptBundle: Represents a bundle object that does Js Minification.
  • StyleBundle: Represents a bundle object that does CSS minification.
  • BundleTable: Static holder class for the default bundle collection.
Additional : MSDN

Within Views folder , add reference to web.config. Adding reference to web.config will support bundling Razor Html helpers: @Scripts on pages.
<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <add namespace="FileUpload_MVC" />
      <add namespace="System.Web.Optimization" />
    </namespaces>
  </pages>
</system.web.webPages.razor>

 

Within Views folder, add reference to web.config file. This will support bundling Razor Html helpers @Styles on pages.

 

<system.web>
   <pages>
     <namespaces>
       <add namespace="System.Web.Optimization" />
     </namespaces>
   </pages>
    
   '''

 </system.web>






Within App_Start folder, create a class named whatever you prefer; I will keep to convention and create a class called: BundlesConfig, which it’s signature expects a Bundlecollection.

I could call the class MyBundlesConfig, which it’s signature expects a Bundlecollection.

imageimage











Bundling JavaScript and CSS files.

Add a static method to BundlesConfig which its signature accepts a BundleCollection type.

Create respective bundle objects, expecting a string argument. String argument represents a virtual path where bundling files are located.

Fictitious application relative URLs (“~/url”) are allowed as parameters. Could be thought as a namespace, so (~/MyFictitiousUrl) could be used, and doesn’t necessarily exist as a path within the file structure.

var scriptBundle = new ScriptBundle(“~/bundles/Scripts”);;
var styleBundle = new StyleBundel(“~/bundles/Styles”);


Possible taking advantage of CDN by passing the path of a Content Delivery Network as the second parameter:

var scriptBundle = new ScriptBundle(“~/bundles/Scripts”,”http://MyCDN”);





Include a set of files to be included in the bundle object.

var scriptFiles = new string[]  { “~/Scripts/*.js” };
var styleFiles = new string[] { “~/Content/*.css” };
scriptBundle.Include(scriptFiles );
styleBundle .Include(styleFiles );

Possible passing only a string argument:

scriptBundle.Include(“~/Scripts/*.js”);
styleBundle .Include(“~/Content/*.css”);


Above, the scriptBundle object will collect all JavaScript files located within the Scripts folder. styleBundle object will collect all CSS files located within the Content folder.

Add bundle objects to BundleCollection.

bundles.Add(scriptBundle);
bundles.Add(styleBundle);




BundleConfig.cs


namespace FileUpload_MVC.App_Start
{
    public class BundlesConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            var scriptBundle = new ScriptBundle("~/bundles/Scripts");

            var scriptFiles = new string[] { "~/Scripts/*.js" };

            scriptBundle.Include(scriptFiles);

            var styleBundle = new StyleBundle("~/bundles/Styles");
            styleBundle.Include("~/Content/*.css");

            bundles.Add(scriptBundle);
            bundles.Add(styleBundle);
        }
    }
}

Or… Using IncludeDirectory()

namespace FileUpload_MVC.App_Start
{
    public class BundlesConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            var scriptBundle = new ScriptBundle("~/bundles/Scripts");

            scriptBundle.IncludeDirectory("~/Scripts", "*.js", true);

            var styleBundle = new StyleBundle("~/bundles/Styles");
            styleBundle.IncludeDirectory("~/Content", "*.css", true);

            bundles.Add(scriptBundle);
            bundles.Add(styleBundle);
        }
    }
}






With help of Razor Html Bundling helpers, add Bundling to Razor View:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>deDogs - File Upload Appication</title>

    @Styles.Render("~/bundles/Styles")

    <script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>

    <div>
        @RenderBody()
        <hr />
        <footer></footer>
    </div>

    @Scripts.Render("~/bundles/Scripts")
</body>
</html>






Within the Global.asax.cs file, register calling RegisterBundles(BundleCollection bundles).

 

Reference System.Web.Optimization and passing a Bundles collection. BundleTable is a static holder class for the default bundle collection.

 

namespace FileUpload_MVC
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundlesConfig.RegisterBundles(BundleTable.Bundles);

        }
    }
}


Possible to set BundleTable.EnableOptimizations: return true if bundling and minification of bundle references is enabled; otherwise, false.


Bundling and Minification


This post is for the purpose of my notes only.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”


Henry Ford

No comments:

Post a Comment