Script and Style Bundles


The following is the default code snippet for the BundleConfig.cs file.

using System.Web.Optimization;

public class BundleConfig  
    // For more information on Bundling, visit  
    public static void RegisterBundles(BundleCollection bundles)  
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
    // Use the development version of Modernizr to develop with and learn from. Then, when you're  
    // ready for production, use the build tool at to pick only the tests you need.  
    bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(  

    bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));  

    bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(  

Bundles are registered in the Global.asax file inside the Application_Start() method:

using System.Web.Optimization;

protected void Application_Start() 

Bundles should be rendered in your Views as so:

@using System.Web.Optimization


Note that bundling does not occur when you are in development mode (where the compilation Element in the Web.config file is set to debug="true" ). Instead, the Render statements in your Views will include each individual file in a non-bundled, non-minified format, for ease of debugging.

Once the application is in production mode (where the compilation Element in the Web.config file is set to debug="false"), bundling will take place.

This can lead to complications for scripts that reference relative paths of other files, such as references to Twitter Bootstrap's icon files. This can be addressed by using System.Web.Optimization's CssRewriteUrlTransform class:

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

The CssRewriteUrlTransform class will rewrite relative Urls within the bundled files to absolute paths, so that the references will remain intact after the calling reference is moved to the location of the bundle (e.g. using the above code, moving from "~/Content/css/bootstrap.css" to "~/bundles/css/bootstrap.css").