How to use moment.js library in angular 2 typescript app?
Update April 2017:
As of version 2.13.0, Moment includes a typescript definition file. https://momentjs.com/docs/#/use-it/typescript/
Just install it with npm, in your console type
npm install --save moment
And then in your Angular app, import is as easy as this:
import * as moment from 'moment';
That's it, you get full Typescript support!
Bonus edit: To type a variable or property as Moment
in Typescript you can do this e.g.:
let myMoment: moment.Moment = moment("someDate");
moment
is a third party global resource. The moment object lives on window
in the browser. Therefor it is not correct to import
it in your angular2 application. Instead include the <script>
tag in your html that will load the moment.js file.
To make TypeScript happy you can add
declare var moment: any;
at the top of your files where you use it to stop the compilation errors, or you can use
///<reference path="./path/to/moment.d.ts" />
or use tsd to install the moment.d.ts file which TypeScript might find on it's own.
Example
import {Component} from 'angular2/core';
declare var moment: any;
@Component({
selector: 'example',
template: '<h1>Today is {{today}}</h1>'
})
export class ExampleComponent{
today: string = moment().format('D MMM YYYY');
}
Just be sure to add the script tag in your html or moment won't exist.
<script src="node_modules/moment/moment.js" />
Module loading moment
First you would need to setup a module loader such as System.js to load the moment commonjs files
System.config({
...
packages: {
moment: {
map: 'node_modules/moment/moment.js',
type: 'cjs',
defaultExtension: 'js'
}
}
});
Then to import moment into the file where needed use
import * as moment from 'moment';
or
import moment = require('moment');
EDIT:
There are also options with some bundlers such as Webpack or SystemJS builder or Browserify that will keep moment off of the window object. For more information on these, please visit their respective websites for instruction.