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

4

6

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

Quote answered 30/7, 2019 at 3:19 Comment(0)
H
11

As per Aleks comment

const moment= require('moment') 

worked for me.

Hotshot answered 8/4, 2020 at 8:23 Comment(0)
O
4

Change this

import {moment} from 'moment';

to this

  const moment= require('moment') 
Osmosis answered 30/7, 2019 at 3:22 Comment(3)
Try to use const moment = require('moment'). Import syntax might not work in node without extra module.Osmosis
why we must change this ?Falange
Older node versions don't support import syntax out of the box, afaik node 16+ supports import syntaxOsmosis
N
2

You can use this to import moment.

import * as moment from 'moment';
Nylon answered 16/9, 2020 at 3:32 Comment(1)
why we must change this ?Falange
B
0

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

Broider answered 21/12, 2022 at 21:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.