29

I am working on ionic2 project. I have just start using moment.js but I have a weird issue. I have installed in via npm: npm install moment -S.

Then I have used it in my code:

import moment from 'moment'
...
let x = moment()
debugger

On the console I get this funny issue:

> x
< Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _d: Wed Jun 27 2018 12:06:23, …}
> y = moment()
< VM770:1 Uncaught ReferenceError: moment is not defined
    at eval (eval at Phase (phase.ts:13), <anonymous>:1:1)
    at new Phase (phase.ts:13)
    at new Stage (stage.ts:10)
    at new HomePage (home.ts:39)
    at createClass (core.es5.js:10795)
    at createDirectiveInstance (core.es5.js:10621)
    at createViewNodes (core.es5.js:11971)
    at createRootView (core.es5.js:11876)
    at callWithDebugContext (core.es5.js:13007)
    at Object.debugCreateRootView [as createRootView] (core.es5.js:12468)

Why can't I work with moment within the console?

4
  • Since moment() is no longer used in this context ("debugger" is the last line), V8 optimized it away in this context, I guess.
    – woxxom
    Commented Jun 27, 2018 at 9:18
  • I have added let y = moment() after debugger. Same error. Commented Jun 27, 2018 at 9:22
  • If you haven't already, maybe running node in the terminal and requiring moment in there. This is how I did it.
    – thehme
    Commented Aug 8, 2018 at 1:01
  • Can you post the transpiled version of this code? Maybe it will lead to some answers,
    – A1rPun
    Commented Nov 13, 2019 at 1:08

2 Answers 2

45

Could fetch it from browser console like this:

fetch('https://momentjs.com/downloads/moment.min.js')
    .then(response => response.text())
    .then(text => eval(text))

Then you could use it normally there

1
  • It does not allow me for some reason: Refused to connect to 'https://momentjs.com/downloads/moment.min.js' because it violates the following Content Security Policy directive: Commented Mar 9, 2021 at 6:05
14

If the library was not imported in the regular form you can't access it; if you want to use moment() in the Chrome console you can try to open the official site and then go to the console.

In the console you can write something like

moment("20111031", "YYYYMMDD").fromNow(); 

Not the answer you're looking for? Browse other questions tagged or ask your own question.