moment.js moment is undefined

2019-02-16 06:32发布

问题:

I just updated form moment@2.1.0 to moment@2.7.0 in my Ember.js application and now I am getting an error the moment is not defined when I enter moment() into the console or include it in my scripts.

On the docs I saw "Since 2.4.0 the globally exported moment object is deprecated." which I think is the issue here but I am unsure how I can set moment globally in ember so that all of the references to moment() in our code base currently aren't broken.

I have tried updating the line where we were doing require('moment') to var moment = require('moment') but it has the same result. Even if I put a debugger directly after the var moment = ... line and then enter moment() into the console I still get that moment is undefined.

回答1:

You want the Browser section of the new Documentation.

So...

<script src="moment.js"></script>
<script>
    moment().format();
</script>

Edit

Having said that, it looks like this will probably give you the same issue.

It looks like Moment.js is trying to encourage you to use a package manager in order not to dirty the namespace with global variables.

Go read up on CommonJS and AMD, and try and factor it in to your current stack.

You should be doing something like:

var moment = require('moment');

moment().format();

But in order to use require you need a module system like the ones aforementioned.

But

The obvious fix is to rollback your version of Moment.js, so long as you don't need new functionality. How important can an update on a simple time/date library really be?



回答2:

This happens, when before moment.js there is some package manager/loader already on:

You can see that moment detects

  1. module.exports
  2. define.amd

and if there is nothing like this, then global.moment is assigned.

The global variable is actually window. The factory variable is the function below representing the closure of the moment scope.


Two possibilities:

a) ensure that there is NO CommonJS/SystemJS... package manager/loader before <script src="/scripts/moment-with-locales.js">

b) follow @shennan's answer and load the moment by a package manager/loader, e.g. using SystemJS:

SystemJS.import('/scripts/moment-with-locales.js').then(function(moment) {
    moment.locale('fr');
});