Effective Bundling With ASP.NET MVC
In this post, we take a look at some effective bundling techniques to help streamline your ASP.NET MVC application. Ready? Let's go!
Join the DZone community and get the full member experience.
Join For Freebundling and minification have been available in asp.net mvc for a long time. this blog post focuses on problems people have had with bundling and provides working solutions for those who cannot use bundling in asp.net mvc for different reasons. also, some ideas about more effective bundling are presented here.
source code available! the solution with asp.net mvc web application that contains code given here is available in my github repository: gpeipman/aspnetmvcbundleminify . all extensions shown here are available in the extensions folder of the aspnetmvcbundleminify application
default bundle config
let's start with the default bundle config. this is what is generated when we create new asp.net mvc application.
public class bundleconfig{
// for more information on bundling, visit https://go.microsoft.com/fwlink/?linkid=301862
public static void registerbundles(bundlecollection bundles) {
bundles.add(new scriptbundle("~/bundles/jquery").include(
"~/scripts/jquery-{version}.js"));
bundles.add(new scriptbundle("~/bundles/jqueryval").include(
"~/scripts/jquery.validate*"));
// use the development version of modernizr to develop with and learn from. then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.add(new scriptbundle("~/bundles/modernizr").include(
"~/scripts/modernizr-*"));
bundles.add(new scriptbundle("~/bundles/bootstrap").include(
"~/scripts/bootstrap.js"));
bundles.add(new stylebundle("~/content/css").include(
"~/content/bootstrap.css",
"~/content/site.css"));
}
}
the idea here is to have granular bundles but this not what we need in web applications usually. in most cases, we need one bundle for scripts and another for styles. this way we get the number of requests to the web server down. here is the default page of an asp.net mvc application created with visual studio.
optimizing bundles
leaving
modernizr
as an exception, i modify the bundling code to have two general bundles.
public class bundleconfig{
// for more information on bundling, visit https://go.microsoft.com/fwlink/?linkid=301862
public static void registerbundles(bundlecollection bundles) {
bundles.add(new scriptbundle("~/bundles/scripts")
.include("~/scripts/jquery-{version}.js")
.include("~/scripts/jquery.validate*")
.include("~/scripts/bootstrap.js")
);
// use the development version of modernizr to develop with and learn from. then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.add(new scriptbundle("~/bundles/modernizr").include(
"~/scripts/modernizr-*"));
bundles.add(new stylebundle("~/bundles/css").include(
"~/content/bootstrap.css",
"~/content/site.css"));
bundletable.enableoptimizations = true;
}
}
the
enableoptimizations
property tells the bundling to enable optimizations no matter what configuration we are using. this way it is easy to see if bundling works when the application runs with the debug configuration.
solving file ordering issues
even now bundling should work fine. but i have seen some cases when the order of the files in the bundle is incorrect. also, some of my fellow developers have told me about this weird issue. it seems to be an issue with older versions. by default, all bundles use the defaultbundleorderer class. this class uses filesetorderlist to read the files in the bundle.
those who cannot upgrade their solution to the latest version and have file ordering issues can use the custom orderer by master-inspire .
public sealed class asisbundleorderer : ibundleorderer
{
public ienumerable<bundlefile> orderfiles(bundlecontext context, ienumerable<bundlefile> files)
{
return files;
}
}
this class keeps the original order of files in the bundle and adds no unexpected logic. to make it work we just have to assign it to a bundle.
var scriptbundle = new scriptbundle("~/bundles/scripts")
.include("~/scripts/jquery-{version}.js")
.include("~/scripts/jquery.validate*")
.include("~/scripts/bootstrap.js")
.include("~/scripts/application.js");
scriptbundle.orderer = new asisbundleorderer();
bundles.add(scriptbundle);
in case of file ordering problems, the same orderer can be assigned to styles bundle.
fixing image paths in stylesheets
one special case that is not handled in our code are components that refer to images in stylesheets. let's add jquery ui to our application through nuget (yes, it's old but still a good example). jquery ui script is put into the scripts folder or our application. styles with images are added to the content/theme/base folder. there's also a folder for images.
to see if the dialog works, we change the index view of the home controller. i removed most of the default content to keep the view small.
@{
viewbag.title = "home page";
}
<div class="jumbotron">
<h1>asp.net</h1>
<p class="lead">let's test jquery ui dialog</p>
<p><a href="https://asp.net" class="btn btn-primary btn-lg orange">open dialog »</a></p>
</div>
<div id="sampledialog" style="display:none">
<p>i am sample dialog</p>
</div>
we have to add the jquery ui files also to our bundles.
public static void registerbundles(bundlecollection bundles)
{
var scriptbundle = new scriptbundle("~/bundles/scripts")
.include("~/scripts/jquery-{version}.js")
.include("~/scripts/jquery.validate*")
.include("~/scripts/bootstrap.js")
.include("~/scripts/jquery-ui-{version}.js")
.include("~/scripts/application.js");
scriptbundle.orderer = new asisbundleorderer();
bundles.add(scriptbundle);
// use the development version of modernizr to develop with and learn from. then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.add(new scriptbundle("~/bundles/modernizr").include(
"~/scripts/modernizr-*"));
var stylesbundle = new stylebundle("~/bundles/css")
.include("~/content/themes/base/jquery-ui.min.css")
.include("~/content/themes/base/all.css")
.include("~/content/bootstrap.css")
.include("~/content/site.css")
.include("~/content/application.css");
stylesbundle.orderer = new asisbundleorderer();
bundles.add(stylesbundle);
bundletable.enableoptimizations = true;
}
when opening the view in the browser and clicking the open dialog button with developer tools open, we can see that some files are missing.
as the styles bundle has a custom virtual path, the files are not found anymore, as their location is not updated in css.
the solution is simple. we can use transforms on the files we add to bundles. for css, there is the cssrewriteurltransform class. let's add files to the styles bundle using this transform.
var stylesbundle = new stylebundle("~/bundles/css")
.include("~/content/themes/base/jquery-ui.min.css", new cssrewriteurltransform())
.include("~/content/themes/base/all.css", new cssrewriteurltransform())
.include("~/content/bootstrap.css", new cssrewriteurltransform())
.include("~/content/site.css", new cssrewriteurltransform())
.include("~/content/application.css", new cssrewriteurltransform());
and here is the result.
images used in stylesheets now have the correct paths.
i have issues with css path transform
some older mvc applications may use a buggy css transform class. for those, i have a replacement class available. it's taken from a stackoverflow thread,
mvc4 stylebundle not resolving images
. just use it in place of the
cssurlrewritetransform
class.
public void process(bundlecontext context, bundleresponse response)
{
regex pattern = new regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", regexoptions.ignorecase);
response.content = string.empty;
// open each of the files
foreach (bundlefile bfile in response.files)
{
var file = bfile.virtualfile;
using (var reader = new streamreader(file.open()))
{
var contents = reader.readtoend();
// apply the regex to the file (to change relative paths)
var matches = pattern.matches(contents);
if (matches.count > 0)
{
var directorypath = virtualpathutility.getdirectory(file.virtualpath);
foreach (match match in matches)
{
// this is a path that is relative to the css file
var imagerelativepath = match.groups[2].value;
// get the image virtual path
var imagevirtualpath = virtualpathutility.combine(directorypath, imagerelativepath);
// convert the image virtual path to absolute
var quote = match.groups[1].value;
var replace = string.format("url({0}{1}{0})", quote, virtualpathutility.toabsolute(imagevirtualpath));
contents = contents.replace(match.groups[0].value, replace);
}
}
// copy the result into the response.
response.content = string.format("{0}\r\n{1}", response.content, contents);
}
}
}
improving bundling code
our bundles work now and it's time to make the code look better. we can get rid of assigning the orderer to bundles by defining ordered bundle classes.
public class orderedscriptbundle : scriptbundle
{
public orderedscriptbundle(string virtualpath) : this(virtualpath, null)
{
}
public orderedscriptbundle(string virtualpath, string cdnpath) : base(virtualpath, cdnpath)
{
orderer = new asisbundleorderer();
}
}
public class orderedstylebundle : stylebundle
{
public orderedstylebundle(string virtualpath) : this(virtualpath, null)
{
}
public orderedstylebundle(string virtualpath, string cdnpath) : base(virtualpath, cdnpath)
{
orderer = new asisbundleorderer();
}
}
there's also one repeated this - including the css path transform. for this, we can write an extension method to keep our bundling code shorter.
public static class bundleextensions
{
public static bundle includewithrewrite(this bundle bundle, string virtualpath)
{
bundle.include(virtualpath, new cssrewriteurltransform());
return bundle;
}
}
using ordered bundle classes and path transform extension methods, we can write our bundle config class as shown here.
public static void registerbundles(bundlecollection bundles)
{
var scriptbundle = new orderedscriptbundle("~/bundles/scripts")
.include("~/scripts/jquery-{version}.js")
.include("~/scripts/jquery.validate*")
.include("~/scripts/bootstrap.js")
.include("~/scripts/jquery-ui-{version}.js")
.include("~/scripts/application.js");
bundles.add(scriptbundle);
// use the development version of modernizr to develop with and learn from. then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.add(new scriptbundle("~/bundles/modernizr").include(
"~/scripts/modernizr-*"));
var stylesbundle = new orderedstylebundle("~/bundles/css")
.includewithrewrite("~/content/themes/base/jquery-ui.min.css")
.includewithrewrite("~/content/themes/base/all.css")
.includewithrewrite("~/content/bootstrap.css")
.includewithrewrite("~/content/site.css")
.includewithrewrite("~/content/application.css");
bundles.add(stylesbundle);
bundletable.enableoptimizations = true;
using this new code we still have our bundle config almost like it was before, but it works smarter.
wrapping up
although there have been good and bad times in asp.net mvc bundling, there are still solutions available for all the common problems people have faced. we were able to solve file ordering and css path transform problems. also, we have a replacement class for path transforms to use with some problematic releases. to close the topic, we created our own ordered bundle classes and version of the
include()
method that applies path transform to css files automatically. the tricks given here should solve most of the problems we have faced with bunding in classic asp.net mvc applications.
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
-
Writing a Vector Database in a Week in Rust
-
Structured Logging
-
Microservices With Apache Camel and Quarkus (Part 2)
Comments