Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - 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:

enter image description here

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

module.exports = require("npm:[email protected]/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?

https://github.com/angular-ui/ui-calendar/issues/154

https://github.com/jkuri/ng2-datepicker/issues/5

Typescript module systems on momentJS behaving strangely

https://github.com/dbushell/Pikaday/issues/153

Thanks!

question from:https://stackoverflow.com/questions/35272832/systemjs-moment-is-not-a-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...