In the following post I will show how to use momentJS in a closure compiled Angular application.
One of the challenges when bundling third party libraries using the Closure compiler is that the library might not be compatible with Closure (ADVANCED_OPTIMIZATIONS).
MomentJS is an example of a very popular library used by a lot of Angular applications.
In the following sample I will show how to integrate moment 2.13.0 with my Angular bundle.
Component
The first step is to import moment from my component.
Normally I would import moment as “import * as moment from 'moment'”, but this approach gave me a few issues with Closure.
Instead I had to do: import from 'moment'.
The downside to this is that I don't get to benefit from typings. Notice I am also declaring a global moment variable to refer to window.moment.
Now that moment is imported, I can start using it.
In my simple example I am just formatting a date using moment().format('dddd').
Externs
To protect the global moment variable I had to declare an extern. I defined my moment extern in a separate file like so:
Configuration
The final step is to define configuration to tell the Closure compiler how to compile the application. My configurations can be found below:
I have added my code to Github if you are interested in trying it yourself.