Error using moment.js with alpha46 Ionic 2

I’ve been using the moment.js library within my two Ionic 2 projects and it has worked ok without problems. I’ve now upgraded my projects (from alpha40 to alpha46) and I now get an error when I try to use the library.

In my package.json I have moment specified as a dependency:

"moment": "^2.10.6"

This seems to bring the package in ok (its listed under node-modules in my project).

In my code I import it like this at the top:

import * as moment from 'moment'; 

but when I try to use it i.e

this.currentDate = new Date();
this.currentDateMoment = new moment(this.currentDate);

I get an error of:

TypeError: Object is not a constructor (evaluating ‘new moment(this.currentDate)’)

Like I said, this all worked fine in alpha40. Anyone have any ideas what I need to change to get this to work again? Is is something to do with new Ionic 2 project structure or something (i.e my code being in the app folder instead of the www folder ?)

I have a funny feeling the Conference app used to use the moment.js library was well but it looks like it doesn’t any more.

Have you tried to import moment like this?

import moment from 'moment';
1 Like

Ahh! That worked - thanks!

Hi, sorry if i’m being dumb but why using the following doesn’t work?:

import {moment} from ‘moment’;

I’m no expert on ES6 exports/imports but I think it is because moment.js exports the moment object as the default export.

Like this:

export default moment;

in this file

So to import it you must write

import moment from 'moment';

But you could really call your variable anything you like, like

import myGreatestMoment from 'moment';

or something.

But if moment.js had exported the object as just

export moment;

Then you would need to import it using

import { moment } from 'moment';

Please correct me if I’m wrong.

So this import uses the default import and put it in the moment_var variable

import moment_var from ‘moment’;

This one searchs for an export named moment and imports it like that

import {moment} from ‘moment’;

And this one does the same as above but rename the variable to moment_var

import {moment} as moment_var from ‘moment’;

That’s as i understand the use cases of the import/export so far.

This has changed again in alpha47. I have now had to change my code back to the way it was prior to alpha46 i.e

import * as moment from ‘moment’;

Hi All,

I cannot get moment to work with Ionic 2 (Angular 2 RC 4). Any ideas?

Please see this for details.