When to use bundles in MVC4

Ricardo Polo Jaramillo picture Ricardo Polo Jaramillo · Aug 19, 2012 · Viewed 7.1k times · Source

In MVC 4 I can use @Styles.Render("~/Content/css") to called a bundle of CSS files defined BundleConfig file instead of calling the CSS directly.

When should we use bundle instead of calling directly the file? I understand it clearly when we have various CSS files to simplify the code. But if there is a single CSS file, should we use a bundle or call it directly?

Answer

Martin Devillers picture Martin Devillers · Aug 19, 2012

Combining multiple files is only one of the various interesting features of bundling.

For instance, bundles allow you to apply various transformations (e.g. LESS for CSS; Minification; Obfuscation for JS; etc).

Another nice feature is its built in caching mechanism. This ensures that clients will only retrieve a specific version of your bundle once. Any change to your bundle will be picked up by the client on the next request.

Bundles can also be used for run-time swapping of CSS or JS files. For instance, serving debug version of a JS framework on your development environment, while serving a minified version on your production environment. The switch can be made in your Global.asax.cs using any custom logic you like (e.g. Web.config parameter; compiler conditionals; etc)