How to enable bundling and minification of CSS/JS in ASP.NET

This is a pretty neat way to bundle and optimize your CSS and Javascript files within your ASP.NET application.

  1. Install the nuget package Microsoft ASP.NET Web Optimization Framework
  2. Add a new class inside the App_Start folder > BundleConfig.cs
  3. Register/group your CSS and JS files the way you want it
    public class BundleConfig
    {
       public static void RegisterBundles(BundleCollection bundles)
       {
          bundles.Add(new StyleBundle("~/bundles/abovethefoldcss").Include(
             "~/Content/css/somecss.css", 
             "~/Content/css/anothercss.css"));
          bundles.Add(new StyleBundle("~/bundles/belowthefoldcss").Include(
             "~/Content/css/bootstrap.css", 
             "~/Content/css/font-awesome.css"));
          bundles.Add(new ScriptBundle("~/bundles/js").Include(
             "~/Scripts/js/jquery.js", 
             "~/Scripts/js/bootstrap.js"));
       }
    }
  4. Call your RegisterBundles method from the Global.asax.cs
    void Application_Start(object sender, EventArgs e)
    {
       BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
  5. Render your bundles inside your view
    <!DOCTYPE html>
    <html lang="en">
    <head>   
       @Styles.Render("~/bundles/abovethefoldcss")
    </head>
    <body>
    
       @Styles.Render("~/bundles/belowthefoldcss")
       @Scripts.Render("~/bundles/js")
    </body>
    <html>

Please note if you are running on debug mode, it will load the files separately. Bundling and minification occurs for when compilation is on release mode.

Discover more from Nicola Ayan

Subscribe now to keep reading and get access to the full archive.

Continue reading