mautrok mautrok - 2 months ago 692
TypeScript Question

How to import moment.js angular2

I'm trying to import moment.js into my angular2 application.
First of all I have followed this guide, and I've found this answer but even if I've tried to follow the proposed solutions I'm still unable to import moment.js.
The package is present, and in fact my IDE (visual studio) is able to find the moment.d.ts file without any problem, but when I run my application with npm start, I get this two errors in the console:


"NetworkError: 404 Not Found - http://localhost:3000/node_modules/moment/"
/node_m...moment/
Error: patchProperty/desc.set/wrapFn@http://localhost:3000/node_modules/zone.js/dist/zone.js:769:27
Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:356:24
Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:256:29
ZoneTask/this.invoke@http://localhost:3000/node_modules/zone.js/dist/zone.js:423:29

Error loading http://localhost:3000/node_modules/moment as "moment" from 'my file'


I've tried to import moment in this way

import * as moment from 'moment'


and in this way to

import * as moment from 'moment/moment.d'


but nothing, I'm still get the error. My SystemJs'map property is this one

var map = {
'app': 'app', // 'dist',
'@angular': 'node_modules/@angular',
'services': 'app/service',
'moment': 'node_modules/moment',//moment.js
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs'
};


If I try to install with typings i get this error:


Typings for "moment" already exist in "node_modules/moment/moment.d.ts". You should let TypeScript resolve the packaged typings and uninstall the copy installed by Typings


so I had uninstalled it, and retype the commands, well I get this error


typings ERR! message Unable to find "moment" ("npm") in the registry.


so is ther a way to get out from this dilemma?

Answer

Firstly, install the moment package via npm:

npm install moment --save

Secondly change your systemjs config (2 lines):

(function (global) {
  // map tells the System loader where to look for things
  var map = {
    'app': 'app', // 'dist',
    '@angular': 'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs': 'node_modules/rxjs',
    'moment': 'node_modules/moment', <== add this line
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app': { main: 'main.js', defaultExtension: 'js' },
    'rxjs': { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
    'moment': { main: 'moment.js', defaultExtension: 'js' } <== add this line
  };

Then you can use it:

import * as moment from 'moment';

Typings will be available from node_modules/moment/moment.d.ts

Comments