Introduction
When we write angular application we cannot minimize javascript file as we do regularly. This is because in angular most of the injectables are declared as strings bus used as properties. If we would minimize the js files the properties would be changes into letters (a, b,etc...) and angular won't be able to find these injectables declarations.
In MVC4 we can use bundles to minimize js and css files. Unfortunately to my experience these classes are not working well with O.O javascript. I have also encountered other problems with naming conventions in files. If error is thrown while minimizing js file, the file will be served, but, will include stack trace of the error appended into the beginning of the javascript file, and this is not good to say the least.
YUI Compressor
Yahoo has a pretty good compressor engine that allows to do the same and even more. Luckily, in MVC4 we can import YUI dlls to our project and override default compression engine of MVC bundles to use YUI instead. It can the be configured to leave angular injectables as-is while compressing and concatenating all the rest.
Importing YUI
First of all be sure you use 4.5 framework as YUI dlls requires that. Open "Package Manager Console" and enter the following line:
install-package YUICompressor.NET.Web.Optimization
This will install all the prerequisites and the YUI dlls.
Switching to YUI
Now we should override the default behavior of the bundles and direct MVC to use YUI minimization engine instead.
Inside BundleConfig.cs file we should create javascript compressor configuration instance and set ObfuscateJavascript = true. This configuration will direct YUI engine to leave the variables naming as is.
var jsCompressorConfig = new JavaScriptCompressorConfig
{
ObfuscateJavascript = true
};
var jsTransform = new YuiCompressorTransform(jsCompressorConfig);
We now can start switching our bundles to work with YUI.
Assuming we keep naming conventions in our project file system we can bundle our js files as follows:
bundles.Add(new Bundle("~/js/controllers.js", jsTransform).Include(
"~/js/controllers/controllers.js",
"~/js/controllers/*-controller.js"));
bundles.Add(new Bundle("~/js/filters.js", jsTransform).Include(
"~/js/filters/filters.js",
"~/js/filters/*-filter.js"));
Taking into account that all of our controllers end with -controller.js we now have bundle that will include all the controllers in the controllers directory without the need to add anything after creating the new controller.
No comments:
Post a Comment