:::: MENU ::::

Thursday, July 21, 2016

No one likes an application or site that loads slowly.
Thankfully, as developers, there are things that we can do to help mitigate load times and often turn seconds into milliseconds. Web performance is such a large subject, but this post is going to focus on bundling and minifying resources, particularly CSS and Javascript files within ASP.NET Core Applications.

What's Changed in Bundling in .NET Core?

If you have been working in the ASP.NET ecosystem for the past few years, you know that you have been able to rely on the built-in bundling and minification that it offered. While it may not have been the friendliest thing in the world, it generally worked as follows within a BundleConfig.cs file:
public static void RegisterBundles(BundleCollection bundles)  
{
     // Bundling jQuery 
     bundles.Add(new ScriptBundle("~/bundles/jquery")
            .Include("~/Scripts/jquery-{version}.js"));
     bundles.Add(new ScriptBundle("~/bundles/jqueryval")
            .Include("~/Scripts/jquery.validate*"));
     // Bundling CSS files
     bundles.Add(new StyleBundle("~/Content/css")
            .Include("~/Content/site.css"));
}
This would handling smashing all of your files together as a single, cachable resource that you user could download once as opposed to making a request for every single file and dependency in your application, which saved them time.
However, in this new ASP.NET Core world, long gone is the BundleConfig.cs file.

Enter Grunt and Gulp

As ASP.NET Core became more lean and modular, many of the built-in features like bundling were removed and those tasks were delegated to other tools and utilities like Grunt and Gulp.
Grunt and Gulp are both Javascript-based tools for running tasks and building respectively. These tools are easily integrated into ASP.NET Core projects and incredibly useful for performing any type of file manipulation, automation and other tasks like bundling and minifying files as mentioned in the documentation.
The problem here is that it often isn't pretty or easy to look at, especially for folks that aren't familiar with Javascript:
// Defining dependencies
var gulp = require("gulp"),  
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify");
// Defining paths
var paths = {  
    js: webroot + "js/**/*.js",
    minJs: webroot + "js/**/*.min.js",
    css: webroot + "css/**/*.css",
    minCss: webroot + "css/**/*.min.css",
    concatJsDest: webroot + "js/site.min.js",
    concatCssDest: webroot + "css/site.min.css"
};
// Bundling (via concat()) and minifying (via uglify()) Javascript
gulp.task("min:js", function () {  
    return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
        .pipe(concat(paths.concatJsDest))
        .pipe(uglify())
        .pipe(gulp.dest("."));
});
// Bundling (via concat()) and minifying (via cssmin()) Javascript
gulp.task("min:css", function () {  
    return gulp.src([paths.css, "!" + paths.minCss])
        .pipe(concat(paths.concatCssDest))
        .pipe(cssmin())
        .pipe(gulp.dest("."));
});
You can then schedule tasks like these to run on certain events (i.e. Build, Publish, etc.) to ensure that your files stay in sync.
But what if you aren't a big fan of Javascript or this all just looks too complicated? Surely there must be an easier way?

An Easier Way: The Bundler and Minifier Extension.

Mads Kristensen, the mad scientist behind Visual Studio extensibility decided to automate this process with the release of the Bundler and Minifier Extension, which integrates into Visual Studio and allows you to easily select and bundle the files you need without writing a line of code.
Some of the current features are as follows :
  • Bundles CSS, JavaScript or HTML files into a single output file
  • Saving a source file triggers re-bundling automatically
  • Support for globbing patterns
  • MSBuild support for CI scenarios supported
  • Minify individual or bundled CSS, JavaScript and HTML files
  • Minification options for each language is customizable
  • Shows a watermark when opening a generated file
  • Task Runner Explorer integration
  • Command line support
  • Shortcut to update all bundles in solution
  • Suppress output file generation
  • Convert to Gulp
After installing the extension, you select all of the specific files that you want to include within a bundle and use the Bundle and Minify Files option from the extension :
This will prompt to you name your bundle and choose a location to save it at. You'll then notice a new file within your project called bundleconfig.json which looks like the following :
[
  {
    "outputFileName": "wwwroot/app/bundle.js",
    "inputFiles": [
      "wwwroot/lib/jquery/dist/jquery.js",
      "wwwroot/lib/bootstrap/dist/js/bootstrap.js",
      "wwwroot/lib/jquery-validation/dist/jquery.validate.js",
      "wwwroot/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js" 
    ]
  }
]
NOTE: The order in which the files are selected will determine the order that they appear in within the bundle, so if you have any dependencies, ensure you take that into account.
Now the previous step will simply bundle your files, if you want to minify the bundle, then you need to indicate that within the bundleconfig.json file. Simply add a minify block like the following to your existing bundle to indicate you want it minified :
[
  {
    "outputFileName": "wwwroot/app/bundle.js",
    "inputFiles": [
      "wwwroot/lib/jquery/dist/jquery.js",
      "wwwroot/lib/bootstrap/dist/js/bootstrap.js",
      "wwwroot/lib/jquery-validation/dist/jquery.validate.js",
      "wwwroot/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js" 
    ],
    "minify": {
      "enabled": true
    }
  }
]

Automating Bundles

Finally, if you want to automate this process, you can schedule a task to run whenever your application is built to ensure that your bundles reflect any changes within your application.
To do this, you'll need to do the following :
  • Open the Task Runner Explorer (via Tools > Task Runner Explorer).
  • Right-click on the Update All Files option below bundleconfig.json.
  • Select your preferred binding from the Bindings context menu.

That's all there is to it.

While bundling and minification may be a bit different that you may have been accustomed to, it's going to be one of the smaller things that you have to worry about transitioning to this new modular ASP.NET Core world.
Regardless of the approach that you choose, bundling and minification can translate into smaller requests and quicker load times for your users and as demonstrated here, it hardly takes any work at all.