How to handle scripts bundling and minification in Umbraco CMS

There are many techniques on how to make your website scripts faster.

In this article I'll cover bundling and minification technique in Umbraco using native Microsoft.AspNet.Web.Optimization library.

Before we start make sure you've read my previous post on - How to handle bundling and minification in ASP .NET . You should follow the same steps:

  • Installing the Microsoft.AspNet.Web.Optimization package
  • Prepare BundleConfig.cs class
  • Create js/css bundles inside BundleConfig.cs
  • Force optimization
  • Wire up bundling with Umbraco - Register the bundle engine
  • Using bundling and minification in Razor Views

How to register bundles in Umbraco?

The best way is to use Umbraco Composing technique - there is a great tutorial here

First, let's create a folder for new component called \Compose.

Then, inside you need to create a class called (for instance) BundleComponent with Initialize() method.

This great place to wire BundleConfig during application startup: 

BundleConfig.RegisterBundles(BundleTable.Bundles);

Full component looks as follows: 

public class BundleComponent : IComponent
{
    public void Initialize()
    {
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        _logger.Info<BundleComponent>("Registering bundles");
    }

    public void Terminate()
    {

    }
}

Additionally, you can add a logger via Dependency injection (Umbraco.Core.Logging) to the above component - to see if bundling event was fired.

public class BundleComponent : IComponent
{
    private readonly ILogger _logger;

    public BundleComponent(ILogger logger)
    {
        _logger = logger;
    }

    public void Initialize()
    {
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        _logger.Info<BundleComponent>("Registering bundles");
    }

    public void Terminate()
    {

    }
}

That's it - Happy Umbraco bundling & minification 😀