MVC Bundle and Minification at Sitecore

2014/11/12 min read
bookmark this
Responsive image

This blog is trying to show how to enable ASP.NET Bundle & Minification for Javascript and CSS.

 Following example is based on these technologies.

  • Sitecore 7.2
  • ASP.NET MVC 5
  • Visual Studio 2013

1. Web.config

add following module to webconfig modules section.

<system.webServer>
    <remove name="BundleModule"/>
      <add type="System.Web.Optimization.BundleModule" name="BundleModule"/>

2. register bundle to sitecore- part 1

Part of register bundle, you need to add following code to register bundle to sitecore.

Note that you don't need to add anything at Global.ascx class to register bundle as default ASP.NET MVC bundle behavior.

using Sitecore;
using Sitecore.Pipelines;
using System.Web.Optimization;

namespace YourNamespace
{
    /// 
    /// SiteCore bundle register
    /// 
    public class RegisterBundles
    {
        [UsedImplicitly]
        public virtual void Process(PipelineArgs args)
        {
            Bundles(BundleTable.Bundles);
        }

        /// 
        /// add bundle collection when application start
        /// at here, you can add as regular 
        /// 
        ///
        private void Bundles(BundleCollection bundles)
        {

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

        }
    }
}

2. register bundle to sitecore- part 2

You need to add following config, anyname is fine, Sitecore will grap it. Let's say, bundle.config. Put the file under, {YourAspnetWebSiteFolder}/App_Config/Include/{PutHere}. Or put any location that your site load the Sitecore config.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="IgnoreUrlPrefixes"
               value="(all other sitecore paths here)|/vendors/js|/vendors/css"/>
    </settings>
    <pipelines>
      <initialize>
        <processor patch:before="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeGlobalFilters, Sitecore.Mvc']"
                   type="YourNamespace.RegisterBundles, YourDll" />
      </initialize>
    </pipelines>
  </sitecore>
</configuration>

That's it! You should be albe to use ASP.NET Bundle & Minification now as following.

@Scripts.Render("~/bundles/jquery")

Referenced

Sitecore with MVC4