Using moment.js in Angular 2 typescript application

DanyUP picture DanyUP · Feb 7, 2016 · Viewed 20.1k times · Source

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:

    System.config({
        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 and 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 moment(). 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

Vladimir Trifonov picture Vladimir Trifonov · Feb 7, 2016
import * as moment_ from 'moment';
const moment:moment.MomentStatic = (<any>moment_)['default'] || moment_;