How to use moment.js library in angular 2 typescript app?
I tried to use it with typescript bindings:
npm install moment --save
typings install moment --ambient -- save
test.ts:
import {moment} from 'moment/moment';
And without:
npm install moment --save
test.ts:
var moment = require('moment/moment');
But when I call moment.format(), I get an error. Should be simple, can anybody provide a command line/import combination that would work?
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.
The following worked for me.
First, install the type definitions for moment.
typings install moment --save
(Note: NOT --ambient
)
Then, to work around the lack of a proper export:
import * as moment from 'moment';