Sunday, May 19, 2013

AngularJS + RequireJS

TypeScript has excellent support for AMD / RequireJS and you can see that over here

http://www.youtube.com/watch?v=4AGQpv0MKsA

Now that I am working on throwing AngularJS into the mix it feels a bit awkward to integrate AngularJS / RequireJS / TypeScript.

I've done it before and infact this presentation uses all three:
http://basarat.github.io/TypeScriptDeepDive/
It provides a great sample for you to experiment with if you need to (based on RequireJS + AngularJS seed project https://github.com/tnajdek/angular-requirejs-seed)

It becomes a lot less relevant when you do your bundling and minification on the server e.g. http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification . Let me explain.

There are two reasons behind organization of your script files.

First: 

Items that are declared in the global namespace are available before they are used.
e.g. $ should be available before your code runs e.g. even the init: 
Or for that matter angular should be available before you go on creating your modules. This is the area where RequireJS is still relevant when you use AngularJS. This is the area that can also be solved by ordering in your JS bundles.

Second:

Functions declared are called in order. AngularJS does this inherantly. Any module declaration / service declaration / scope declarations are just declarations. These are executed depending upon the order they are defined as a dependency. e.g

Directives controllers and services all get instantiated (using function calls) before the module gets instantiated. This is a region of overlap between RequireJS and AngularJS and if you are using Angular then RequireJS loses a bit of its charm.

Finally:

The final decision is of course up to you and you will have to make it for your project based on your requirements. If you are using a lot of script tags and don't have a server side alternative then yes, I feel requireJS is a must for you. Otherwise, not so much.

Additionally: 

The angular team itself depends on closure compiler to do its minification (confirmed fact) along with sourcemaps (my assumption) to do its debugging. So they can effectively use a single script tag since the ordering logic is maintained by the closure compiler.