Jason000
Jason000

Reputation: 199

Reference Error: moment is not defined (Using moment.js)

I installed the moment.js library and was about to play around with it a little bit, when i got this error. I've tried many different things, but nothing has worked. Any ideas?

I have a folder that i've installed moment.js into (npm install moment) and i'm running my program (node isDate.js).

import {moment} from 'moment';

function isDate(string) {
    {
        moment(string).format(["MM-DD-YYYY", "YYYY-MM-DD"]);
    }
} exports.isDate = isDate;

ReferenceError: moment is not defined

Upvotes: 6

Views: 39313

Answers (4)

phpaul89
phpaul89

Reputation: 101

In case the other solution proposals don't work out, checking for hoisting behavior might help.

Here's what helped in my particular case.

Using your example code, it would be changing the function declaration:

import * as moment from 'moment';

function isDate(string) {
    return moment(string).format(["MM-DD-YYYY", "YYYY-MM-DD"]);
}

to a function expression:

import * as moment from 'moment';

const isDate = (string) => {
    return moment(string).format(["MM-DD-YYYY", "YYYY-MM-DD"]);
}

This resolved the reference error 'moment is not defined' in our React code base, where the function which uses 'moment' was imported in a component file.

See also 'Function Hoisting': Functions - JavaScript | MDN

Upvotes: 0

Ninja Turtle
Ninja Turtle

Reputation: 1353

You can use this to import moment.

import * as moment from 'moment';

Upvotes: 2

Aleks
Aleks

Reputation: 984

Change this

import {moment} from 'moment';

to this

  const moment= require('moment') 

Upvotes: 4

patil
patil

Reputation: 111

As per Aleks comment

const moment= require('moment') 

worked for me.

Upvotes: 11

Related Questions