DanyUP DanyUP - 1 year ago 126
TypeScript Question

Using moment.js in Angular 2 typescript application

I'm struggling in using moment.js library inside an Angular 2 Typescript app. Even after reading the answer to this question I can't get it to work.

This is what I did so far:

  • I installed moment.js using npm, so I can find the library under node_modules/moment/moment.js

  • I configured System.js to retrieve moment library:

    packages: {
    app: {
    format: 'register',
    defaultExtension: 'js'
    moment: {
    main: 'moment.js',
    type: 'cjs',
    defaultExtension: 'js'
    map: {
    moment: 'node_modules/moment'

  • I installed typescript typings with
    typings install moment-node --ambient --save
    typings install moment --ambient --save
    , so I can see the correct typings inside typings/main/ambient/moment-node and typings/main/ambient/moment

Now, if in my code I use
import * as moment from 'moment';
typescript compilation run smooth and I can see the correct suggestion inside Atom editor (if I start with
I can see year(), month(), etc.). However if I run my code inside the browser, it gives an error saying that 'moment is not a function' (debugging I can see that moment is an object with lots of methods).

If I write
import moment from 'moment';
the code in the browser runs fine, however typescript compilation fails with 'module moment has no default export' and I can't get any suggestion from Atom while writing code.

What am I doing wrong? What's the correct way to import moment.js (and any non typescript library) inside an Angular 2 typescript application?

Answer Source
import * as moment_ from 'moment';
const moment:moment.MomentStatic = (<any>moment_)['default'] || moment_;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download