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.