Post

Less bundling and minification in a C# ASP.NET MVC application

Setting up Less CSS preprocessing with bundling and minification in an ASP.NET MVC project using BundleTransformer.

Standard ASP.NET MVC projects support bundling and minification for CSS and JavaScript out of the box via the Microsoft.AspNet.Web.Optimization framework. Getting Less CSS to work requires a bit more setup.

Step 1: Install BundleTransformer.Less

Install the BundleTransformer.Less NuGet package via the Package Manager Console:

Install-Package BundleTransformer.Less

This automatically pulls in BundleTransformer.Core and JavaScriptEngineSwitcher.Core as dependencies. Avoid the older DotLess package — it’s outdated.

Step 2: Install a JavaScript Engine

Less compilation requires a JavaScript engine. Install JavaScriptEngineSwitcher.Msie:

Install-Package JavaScriptEngineSwitcher.Msie

Configure it in web.config:

<less>
  <jsEngine name="MsieJsEngine"></jsEngine>
</less>

Step 3: Configure the Engine Switcher

Create App_Start/JsEngineSwitcherConfig.cs:

using JavaScriptEngineSwitcher.Core;
using JavaScriptEngineSwitcher.Msie;

namespace JavaScriptEngineSwitcher.Sample.AspNet4.Mvc4
{
    public class JsEngineSwitcherConfig
    {
        public static void Configure(JsEngineSwitcher engineSwitcher)
        {
            engineSwitcher.EngineFactories
                .AddMsie(new MsieSettings
                {
                    UseEcmaScript5Polyfill = true,
                    UseJson2Library = true
                });

            engineSwitcher.DefaultEngineName = MsieJsEngine.EngineName;
        }
    }
}

Step 4: Configure Bundles

Update your BundleConfig.cs RegisterBundles method:

bundles.UseCdn = true;

var nullBuilder = new BundleTransformer.Core.Builders.NullBuilder();
var styleTransformer = new BundleTransformer.Core.Transformers.StyleTransformer();
var scriptTransformer = new BundleTransformer.Core.Transformers.ScriptTransformer();
var nullOrderer = new BundleTransformer.Core.Orderers.NullOrderer();

BundleResolver.Current = new BundleTransformer.Core.Resolvers.CustomBundleResolver();

var commonStylesBundle = new Bundle("~/Bundles/CommonStyles");
commonStylesBundle.Include(
    "~/styles/file-1.less",
    "~/styles/file-2.less"
);
commonStylesBundle.Builder = nullBuilder;
commonStylesBundle.Transforms.Add(styleTransformer);
commonStylesBundle.Orderer = nullOrderer;
bundles.Add(commonStylesBundle);

Then reference the bundle in your views:

@Styles.Render("~/Bundles/CommonStyles")

Example Less Files

file-1.less:

body {
    background-color: tomato;

    .jumbotron h1 { color: lightcoral; }
}

file-2.less:

body {
    .container .jumbotron { background-color: lightgoldenrodyellow; }
}

Minification and compression activate automatically when <compilation debug="false" /> is set in web.config.

← Back to all posts