Minify resources with source map at runtime using Web Essential

By Ugo Lattanzi on Jan. 8th , in aspnetmvc webdev | comments

Share On Google Share On Facebook Share On Twitter

In one of the last versions of Web Essential Tools, Microsoft released one of my favorite features for the web development. I’m talking about the opportunity to create a bundle resource at runtime with the support of SourceMap.

The first step to try this cool feature is to install the Visual Studio plugin so, download it from here

After the installation Visual Studio offers you new features that are not available in the standalone version. In fact, after right clicking on a web resource (css, js, etc) in the solution explorer, you have a new “item” named Web Essential:

001

 

What I love most in this extension is the easy way to create the combined and minified resources (really, I’m not in love with the web optimization packages included in ASP.NET MVC 4).

What does it give us?

As you can see in both items there is the SourceMap, but what is it? Source Map is a cool feature, actually supported just by Google Chrome, that allows you to understand the correct position (i.e. line of an error) in a Javascript file starting from a combined file.

I think that feature is a killer feature for frontend developers because some errors happened in production and, in some cases, you are not able to reproduce them during the tests.

The first things is to enable that features in chrome, so:

002

 

003

 

From now, everything is easier, select your javascript files, right click and, from WebEssential Items, select “Create Javascript Bundle File”.

004

005

006

 

Drag you bundle into your page, MyExampleJavascriptBundle.min.js in my example, and everything is ready.

From now, every time you change and save the files you selected for the bundle, Visual Studio will automatically update it; it means that minified and source map will always be up to date with the original resources without doing anything special (How f..ing cool is that?).

As you can see in the image below there are more files that I’ve included in my page (see previous screenshots).

007

In fact, I didn’t added the files 001.js and 002.js but only the MyExampleJavascriptBundle.min.js.

How is it possible? The reason is really simple; inside the MyExampleJavascriptBundle.min.js, Visual Studio added a line with the path of Source Map that includes the original not combined files.

Chrome understands this behavior and shows you the source files (only if you use the developer tools bar).

If you like it and you want to understand more about Source Map, take a look here and, if you like Web Essential like me you have to follow Mads on twitter

Stay tuned!