Systemjs - Moment Is Not a Function

I'm using JSPM, AngularJS, TypeScript, SystemJS and ES6 and my project is running pretty well... unless I try to use momentJS.

This is the error I get:

TypeError: moment is not a function

This is part of the code:

import * as moment from 'moment';

More:

var momentInstance = moment(value);

If I debug it, moment is an object not a function:

This is what my moment.js JSPM package looks like:

module.exports = require("npm:moment@2.11.0/moment.js");

I've read a lot and couldn't find a way to solve this... any ideas?

Some things I've read/tried:

How to use momentjs in TypeScript with SystemJS?

Typescript module systems on momentJS behaving strangely

Thanks!

2

5 Answers

Simply remove the grouping (* as) from your import statement:

import moment from 'moment';

Without digging too deeply in to the source code, it looks like moment usually exports a function, that has all kinds of methods and other properties attached to it.

By using * as, you're effectively grabbing all those properties and attaching them to a new object, destroying the original function. Instead, you just want the chief export (export default in ES6, module.exports object in Node.js).

Alternatively, you could do

import moment, * as moments from 'moment';

to get the moment function as moment, and all the other properties on an object called moments. This makes a little less sense when converting ES5 exports like this to ES6 style, because moment will retain the same properties.

2

This worked for me:

import moment from 'moment/src/moment'

A beginner JS mistake that was giving me the same error:

foobar(moment) {
  console.log(moment().whatever());
}

Naming a parameter moment breaks access to the moment() function.

AS plot in the official documentation momentJs my problems were solved via nodeJS approach:

var moment = require('moment');
moment(); //this does not emit the errors

To get moment work as a function, if you are using ES6 and babel, you must import it in this way:

import moment from 'moment'

and not, as written in the documentation

import * as moment from 'moment'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest